Axios和NodeJS,下载图像文件

wqnecbli  于 2023-03-08  发布在  iOS
关注(0)|答案(1)|浏览(180)

从前端,我调用后端服务:

return axios({
  method: 'post',
  url: someUrl/${payload}`,
  responseType: 'stream'
})
  .then((resp) => resp.data)
  .catch((err) => err);

我收到了一个这样的文件:

"����\u0000\u0018Exif\u0000\u0000II*\u0000\b\u0000\u00...(etc)..."

响应是实际IMG二进制文件的双引号字符串。
在另一边,在服务上,我有这个:

const config = {
  method: 'get',
  url: someExternalUrl/{payload},
};

return axios(config)
  .then(function (response) {
    console.log(response.data);
    return response.data;
  })
  .catch(function (error) {
    console.log(error);
  });

当我对www.example.com执行console.log操作时,我看到前端接收到的字符串。response.data I see that string that the frontend receives.
我的问题是:
我怎样才能把二进制文件发送到前端调用?或者我必须在前端转换接收到的字符串吗?

xdnvmnnf

xdnvmnnf1#

您可以修改后端代码以返回响应,如下所示:

const config = {
  method: 'get',
  url: someExternalUrl/{payload},
  responseType: 'arraybuffer'
};

return axios(config)
  .then(function (response) {
    console.log(response.data);
    return response.data;
  })
  .catch(function (error) {
    console.log(error);
  });

responseType设置为arraybuffer,响应将作为二进制缓冲区而不是字符串返回。
在前端,您应该删除代码中的**.then((resp)=〉resp.data)**部分,并将响应直接用作二进制数据:

return axios({
  method: 'post',
  url: someUrl/${payload}`,
  responseType: 'arraybuffer'
})
  .catch((err) => err);

您可以根据需要在前端使用二进制数据。显示一个图像,您可以从二进制数据创建一个blob URL:

const blob = new Blob([binaryData], { type: 'image/jpeg' });
const url = URL.createObjectURL(blob);
// Use the URL to display the image in an <img> element

相关问题