0

我想知道是否有人知道在使用 express/nodejs 时如何从上传的文件中提取文件内容

我有以下代码,很清楚如何将输入通过管道传输到文件流,但是如何将上传反序列化为普通的 javascript 对象?目的是从上传的文件中提取信息并在其他地方使用。理想情况下,我不想通过磁盘上的临时文件。文件格式为json。

app.post("/upload", function(req, res){

    req.pipe(req.busboy);

    req.busboy.on('file', function (fieldname, file, filename) {

        console.log("Uploading: " + filename);
        console.log(file);
        console.log(fieldname);

        // I don't want to go via a file, but straight to a JS object


        //fstream = fs.createWriteStream('/files/' + filename);
        //
        //file.pipe(fstream);
        //
        //fstream.on('close', function () {
        //
        //    res.redirect('back');
        //
        //});
    });
});

文件上传是这样触发的:

var formData = new FormData($('form')[0]);

        e.preventDefault();

        $.ajax({
            url: 'upload',
            type: 'POST',
            data: formData,
            cache: false,
            dataType:'json',
            contentType: false,
            enctype: 'multipart/form-data',
            processData: false,
            success: function (response) {
            }
        });
4

1 回答 1

1

如果您不介意先缓冲文件内容,则可以执行以下操作:

app.post("/upload", function(req, res){
  req.pipe(req.busboy);
  req.busboy.on('file', function (fieldname, file, filename) {
    var buf = '';
    file.on('data', function(d) {
      buf += d;
    }).on('end', function() {
      var val = JSON.parse(buf);
      // use `val` here ...
    }).setEncoding('utf8');
  });
});
于 2015-02-08T23:10:58.293 回答