简体   繁体   中英

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. For fetching the image I am using Axios library.

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' . 'arraybuffer' works too, but 'stream' is even better since you're just passing through the bytes.

By default, I believe axios decodes into a utf-8 string which of course is nonsensical for image binary data.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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