javascript - How to download remote image then upload image as an image file for form submission? - Stack Overflow

There are similar questions like this, this, this, and this, but none help.In Node, the goal is to use

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('.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)
        }

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./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)
        }
Share Improve this question edited Apr 25, 2021 at 20:32 Crashalot asked Apr 23, 2021 at 6:56 CrashalotCrashalot 34.6k63 gold badges284 silver badges460 bronze badges 12
  • Can you clarify what you mean by "something fails between this step and performing the upload"? Can you share the error message? – Arun Kumar Mohan Commented Apr 23, 2021 at 11:19
  • @ArunKumarMohan thanks for the reply. Updated the question: the image gets uploaded in a corrupted state. (Also the image must be uploaded in binary.) – Crashalot Commented Apr 23, 2021 at 15:18
  • Well how are you reading this data on the server? It seems odd to try and append the binary data into a form. Form post data won't typically accept this but, well it depends on how your server is processing the data – Liam Commented Apr 23, 2021 at 15:23
  • I'd suggest something more like this stackoverflow./a/50543235/542251 – Liam Commented Apr 23, 2021 at 15:24
  • 1 @Crashalot I was able to reproduce the issue using httpbin as the API. – Arun Kumar Mohan Commented Apr 26, 2021 at 0:26
 |  Show 7 more ments

2 Answers 2

Reset to default 9 +125

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./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/post', formData, {
    headers: formData.getHeaders(),
  })
  console.log(data)
} catch (error) {
  // handle error
}

You can use the fetch API to fetch the image as a blob object and append it to form data. Then simply upload it to its destination using Axios, ajax, or the fetch API:

    const mediaUrl = "https://pbs.twimg./media/EyGoZkzVoAEpgp9.png"
    fetch(mediaUrl)
      .then((response) => response.blob())
      .then((blob) => {
        // you can also check the mime type before uploading to your server
        if (!['image/jpeg', 'image/gif', 'image/png'].includes(blob?.type)) {
          throw new Error('Invalid image');
        }

        // append to form data
        const formData = new FormData();
        formData.append('image', blob);

        // upload file to server
        uploadFile(formData);
      })
      .catch((error) => {
        console.log('Invalid image')
      });

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744381350a4571446.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信