简体   繁体   中英

How to send files in a formdata from their base64 string in Node.js?

I'm currently working on a Node.js middleware and I need to send a file to an API using a formdata.

I've managed to do this when I use a file on my local storage using fs to create a ReadStream and put it in my formdata.

I use request-promise to send my data:

var formData = {
  'file': fs.createReadStream('myfile.jpg')
}

var options = {
  method: method,
  uri: url,
  formData: formData
}

return rp(options).then(response => response)

Now I don't fully understand what is going on under the hood.

I need to send a file which I only have in a base64 string, and the API is waiting for a file just like I sent "myfile.jpg".

I've tried to send a buffer built from the base64 string:

var buffer = Buffer.from(base64string, 'base64')

var formData = {
  'file': buffer
}

But it didn't work. I could eventually create a binary file from my Buffer and use fs to create a stream from it but I hope there is a better way to achieve this.

Also I'm not confortable working with things I don't understand so if you have any informations on how file streams work with formdatas, I'll take it!

Here is an example using Axios and FormData

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

// Create a new form instance
const form = new FormData();

const file =  fs.readFileSync('./example.jpg');
// or/and
const fileStream = fs.createReadStream('./example.jpg');

// For base64

const buffer = Buffer.from(YOUR_BASE64_STRING, 'base64');

// Create a form and append image with additional fields

form.append('file', file, 'example.jpg');
// or/and
form.append('fileStream', fileStream, 'example.jpg');
// or/and
form.append('buffer', buffer, 'example.jpg');

// Send form data with axios
const response = await axios.post('https://example.com', form, {
    headers: {
        ...form.getHeaders(),
        // some other headers if needed
    },
});

I am not sure if this will work in your setting, but what I have done is create a buffer from the data and then append a "path" property. This property allows request or some other library to guess the type of the data:

  var istream = new Buffer(image, 'base64');
  istream.path = "pic.png";
  server.post( "/upload", {"file":istream}, function(...){} )

The upload worked flawlessly. This depends on your http layer (I guess).

const buffer = Buffer.from(fileBase64Encoded, 'base64');
const form = new FormData();
form.append('image', buffer, fileName);
const headers = {headers: {'Content-Type':`multipart/form-data; boundary=${form.getBoundary()}`}};
return server.post(`${process.env.SERVER}/upload`, form, headers);

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