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
},
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With