使用NodeJS和BusBoy上传文件

3

我正在使用NodeJS上传文件。我的要求是将流读入变量中,以便我可以将其存储到AWS SQS中。我不想将文件存储在磁盘上。这可行吗?我只需要将上传的文件转换为流。我正在使用的代码是(upload.js):

var http = require('http');
var Busboy = require('busboy');

module.exports.UploadImage = function (req, res, next) {

    var busboy = new Busboy({ headers: req.headers });

    // Listen for event when Busboy finds a file to stream.
    busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {

        // We are streaming! Handle chunks
        file.on('data', function (data) {
                // Here we can act on the data chunks streamed.
        });

        // Completed streaming the file.
        file.on('end', function (stream) {
            //Here I need to get the stream to send to SQS
        });
    });

    // Listen for event when Busboy finds a non-file field.
    busboy.on('field', function (fieldname, val) {
            // Do something with non-file field.
    });

    // Listen for event when Busboy is finished parsing the form.
    busboy.on('finish', function () {
        res.statusCode = 200;
        res.end();
    });

    // Pipe the HTTP Request into Busboy.
    req.pipe(busboy);
};

我该如何获取上传的流(stream)?

3个回答

1
在busboy的“file”事件中,您会得到名为“file”的参数,这是一个流,因此您可以将其管道传输。
例如:
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) { 
    file.pipe(streamToSQS)
}

1
我希望这能对你有所帮助。
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
    var filename = "filename";
    s3Helper.pdfUploadToS3(file, filename);
  }
busboy.on('finish', function () {
        res.status(200).json({ 'message': "File uploaded successfully." });
    });
    req.pipe(busboy);

0

当前和现有的论点假设一个人可以将流(文件)发送到能够接收流的某个地方,但实际上接收到的块是在您实现的文件回调方法中接收的。

来自文档:(https://www.npmjs.com/package/busboy)

file.on('data', function(data) {
   // data.length bytes seems to indicate a chunk
   console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
});
      
   
file.on('end', function() {
  console.log('File [' + fieldname + '] Finished');
});


更新:

找到了构造函数文档,第二个参数是可读流。

file(< string >字段名, < 可读流 >流, < string >文件名, < string >传输编码, < string >MIME类型) - 每次发现新的文件表单字段时触发。传输编码包含文件流的'Content-Transfer-Encoding'值。MIME类型包含文件流的'Content-Type'值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接