【问题标题】:nodeJS Convert Buffer to fs.ReadStream objectnodeJS 将 Buffer 转换为 fs.ReadStream 对象
【发布时间】:2020-09-10 08:13:06
【问题描述】:

我正在本地保存一个图像文件,因此我可以使用 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?

或者有更好的方法来解决这个问题?

感谢所有帮助。

【问题讨论】:

    标签: javascript node.js buffer form-data node-streams


    【解决方案1】:

    您可以使用 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) );
    

    【讨论】:

    • 唯一对我有用的解决方案!您是否偶然知道如何使用 got 实现相同的功能? :)
    猜你喜欢
    • 2017-06-16
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    相关资源
    最近更新 更多