nodeJS 将 Buffer 转换为 fs.ReadStream 对象

我正在本地保存一个图像文件,因此我可以使用 fs.createReadStream() 准备它并将其附加到我的 FormData 以将其发送到 REST api。像这样:(我正在使用 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 })

现在我想做同样的事情,但在本地保存文件,而是使用图像缓冲区。我尝试了以下方法,但似乎无法使其工作:

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

如何将 buffer 正确转换为 fs.ReadStream() 对象,以便将其成功发送到 api?

还是有更好的方法来解决这个问题?

感谢所有帮助。

stack overflow nodeJS Convert Buffer to fs.ReadStream object
原文答案

答案:

作者头像

您可以使用 axios 直接从 url 获取流并附加到 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) );
作者头像

设置自定义文件名(获取想要的任何名称)和内容类型,为我工作

const formData = new FormData();
formData.append('file', bufferStream, {filename: 'photo.png', contentType: 'image/png');