广州海外建站推广seo公司
可以通过以下步骤从服务端获取图片:
-
引入axios库:在前端代码中使用axios库来发送HTTP请求。可以通过以下方式引入axios:
import axios from 'axios';
-
发送请求:使用axios发送HTTP请求,获取图片文件的二进制数据。发送请求的代码示例:
axios({method: 'GET',url: 'http://your-domain.com/path/to/image.jpg',responseType: 'arraybuffer' }).then(response => {// 将响应的二进制数据转换为Blob对象const blob = new Blob([response.data], { type: response.headers['content-type'] });// 根据Blob对象生成图片URLconst imgUrl = URL.createObjectURL(blob);// 将图片URL赋值给图片元素的src属性const imgElement = document.querySelector('#my-img');imgElement.src = imgUrl; });
在上面的代码中,
responseType
设置为arraybuffer
,表示响应的数据以二进制数组的形式返回。在响应成功的回调函数中,将响应的二进制数据转换为Blob对象,并根据Blob对象生成图片URL,最后将图片URL赋值给图片元素的src
属性,即可显示图片。
axios({method: 'GET',url: 'http://your-domain.com/path/to/getImage',responseType: 'blob'}).then(response => {// 将响应的二进制数据转换为Blob对象const blob = new Blob([response.data], { type: response.headers['content-type'] });// 根据Blob对象生成图片URL 将图片URL赋值给图片元素的src属性const reader = new FileReader();reader.readAsDataURL(blob);reader.onload = function (e) {imgUrl = e.target.result;// e.target.result 即为base64结果};reader.onerror = (error) => {console.log("图形加载错误");};});
在上面的代码中,responseType
设置为blob
,表示响应的数据以blob对象的形式返回。在响应成功的回调函数中,将响应的二进制数据转换为Blob对象,并根据Blob对象生成图片URL,最后将图片URL赋值给图片元素的src
属性,即可显示图片。
以上虽然设置了blob但是根本上还是图片以二进制的形式传输的,因为所有非json格式,均可以以blob接收在转换成对应格式的图片或文件