简体   繁体   English

获取图像并使用 koa2 发送

[英]Fetch image and send it using koa2

I am trying to fetch an image from external URL and then send it as a response in koa2.我正在尝试从外部 URL 获取图像,然后将其作为 koa2 中的响应发送。 For fetching the image I am using Axios library.为了获取图像,我使用了 Axios 库。

I am trying to do that the following way:我正在尝试通过以下方式做到这一点:

router.get('/get-image', async (ctx, next) => {
    const {authToken} = ctx.query
    const response = await axiosInstance.get(
        'https://www.someurl.com/image/992',
        {
            headers: {
                Authorization: `Bearer ${authToken}`,
            },
        }
    )

    ctx.type = 'image/jpeg'
    ctx.body = response.data
})

But the image I get from that request is not valid.但是我从该请求中获得的图像无效。 It only shows empty rectangle).它只显示空矩形)。

Can someone point me in the right direction on how to resend the received image?有人可以指出我如何重新发送收到的图像的正确方向吗?

Set responseType: 'stream' .设置responseType: 'stream' 'arraybuffer' works too, but 'stream' is even better since you're just passing through the bytes. 'arraybuffer' 也可以工作,但 'stream' 更好,因为您只是通过字节。

By default, I believe axios decodes into a utf-8 string which of course is nonsensical for image binary data.默认情况下,我相信 axios 会解码为 utf-8 字符串,这对于图像二进制数据当然是无意义的。

const response = await axios.get(url, {
  responseType: 'stream',
  ...
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM