Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 766
pcavalet Avatar asked Oct 30 '22 14:10

pcavalet


1 Answers

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
    },
});
like image 158
CyberEternal Avatar answered Nov 03 '22 00:11

CyberEternal