如何下载远程图像然后将图像作为图像文件上传以提交表单? [英] How to download remote image then upload image as an image file for form submission?

查看:20
本文介绍了如何下载远程图像然后将图像作为图像文件上传以提交表单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有类似的问题,比如

There are similar questions like this, this, this, and this, but none help.

In Node, the goal is to use the axios module to download an image from Twitter then upload this image as an image file as part of a form submission.

This code downloads the Twitter image, but the uploaded binary image is corrupted when it reaches the server (also our server).

The image must be uploaded in binary.

A form is required because other fields are also submitted with the binary image. These other form fields were removed to simplify the code sample.

        const axios = require('axios');
        const FormData = require('form-data');

        let response = await axios.get('https://pbs.twimg.com/media/EyGoZkzVoAEpgp9.png', {
                                responseType: 'arraybuffer'
                             });

        let imageBuffer = Buffer.from(response.data, 'binary');    
        let formData = new FormData();          
        formData.append('image', imageBuffer);

        try {
            let response = await axios({
                method: 'post',
                url: serverUrl,
                data: formData,
            });

            // Do stuff with response.data

        } catch (error) {
            console.log(error)
        }

解决方案

You should pass the headers to the axios call using formData.getHeaders() to send a Content-Type header of multipart/form-data. Without it, a Content-Type header of application/x-www-form-urlencoded is sent. You could pass a responseType of stream to the axios call that downloads the image and add the stream to the form data.

You can also use axios.post to simplify the method call.

const url = 'https://pbs.twimg.com/media/EyGoZkzVoAEpgp9.png'
const { data: stream } = await axios.get(url, {
  responseType: 'stream',
})

const formData = new FormData()
formData.append('image', stream)

try {
  const { data } = await axios.post('http://httpbin.org/post', formData, {
    headers: formData.getHeaders(),
  })
  console.log(data)
} catch (error) {
  // handle error
}

这篇关于如何下载远程图像然后将图像作为图像文件上传以提交表单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆