'nodeJS Convert Buffer to fs.ReadStream object
I'm saving an image file locally so I can ready it using fs.createReadStream()
and append it to my FormData
to send it to a REST api. Like this: (I'm using the trello api https://developer.atlassian.com/cloud/trello/rest/#api-cards-id-attachments-post)
const fetch = require('node-fetch');
const Jimp = require('jimp');
const FormData = require('form-data');
// Save file locally
await Jimp.read(imagePNGURL).writeAsync(savedImagePath);
// Append it to the formdata using fs.createReadStream
const formData = new FormData();
formData.append('file', fs.createReadStream(savedImagePath));
// Send formData to api and image gets saved correctly
await fetch('TrelloUrl', { method: 'POST', body: formData })
Now I want to do the same thing but without saving the file locally but by using the image buffer. I've tried the following but I can't seem to make it work:
const fetch = require('node-fetch');
const Jimp = require('jimp');
const FormData = require('form-data');
const stream = require('stream');
// Save file to Buffer
const buffer = await Jimp.read(imagePNGURL).getBufferAsync('image/png');
// Convert buffer to stream
const bufferStream = new stream.PassThrough();
bufferStream.end(buffer);
// Try to append it to the formdata and send it to the api
const formData = new FormData();
formData.append('file', bufferStream); // Results in 400 Bad Request
formData.append('file', bufferStream.read()); // Results in empty image being uploaded
await fetch('TrelloUrl', { method: 'POST', body: formData })
---------
// Also tried to convert the buffer to stream like this:
const { Readable } = require('stream');
const bufferToStream = (buffer) => {
const stream = new Readable();
stream.push(buffer);
stream.push(null);
return stream;
};
formData.append('file', bufferToStream(buffer)); // Results in 400 Bad Request
formData.append('file', bufferToStream(buffer).read(); // Results in empty image being uploaded
How can I convert the buffer
correctly to a fs.ReadStream()
object so I can send it successfully to the api?
Or are there better ways to approach this?
All help is appreciated.
Solution 1:[1]
You can get the stream directly from the url using axios and append to form-data
const axios = require("axios")
const getImageStream = async (url) => {
const response = await axios.get(url, {responseType : "stream"});
if (response.status === 200) {
return response.data
}
}
const formData = new FormData();
formData.append('file', await getImageStream(imagePNGURL) );
Solution 2:[2]
set custom filename (set whatever name do you want) and content-type, worked for me
const formData = new FormData();
formData.append('file', bufferStream, {filename: 'photo.png', contentType: 'image/png');
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Peter Csala |
Solution 2 | MHR |