节点文件传输在images目录中上载x字节的图像,但已损坏

Node File transfer uploads x bytes of image in images directory but is corrupt

本文关键字:字节 图像 已损坏 上载 传输 文件 images 节点      更新时间:2023-09-26

我正在使用Node的Busboy模块来解析文件。首先上传一个文件->将上传的文件推送到images目录。我不知道为什么,但代码正在传输字节,即它确实创建了一个具有适当字节的图像,但当点击文件时,它已损坏。这是我的代码:

var busboy = new Busboy({ headers: req.headers });
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
      console.log('File [' + fieldname + ']: filename: ' + filename + ', encoding: ' + encoding + ', mimetype: ' + mimetype);
      file.on('data', function(data) {
        var fstream = fs.createWriteStream('./images/' + filename); 
        file.pipe(fstream);
        fstream.on('close', function () {
            console.log("Upload Finished of " + filename);
        });
        console.log('File [' + fieldname + '] got ' + data.length + ' bytes');
      });
      file.on('end', function() {
        console.log('File [' + fieldname + '] Finished');
      });
    });

data事件可以多次发射。这里的解决方案很简单:只需将file管道传输到一个可写流一次。例如:

var crypto = require('crypto');
var path = require('path');
// ...
var busboy = new Busboy({ headers: req.headers });
busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
  // You will want to somehow sanitize `filename` if you are going to use
  // it when use it as part of the filename on disk, as it could be maliciously
  // constructed to overwrite to other parts of your filesystem.
  //
  // The solution I use here is to simply hash the filename, but you could
  // use `path.resolve('./images/', filename)` instead and check that the
  // result starts with `__dirname + '/images/'`.
  var ext = path.extname(filename);
  filename = crypto.createHash('sha1')
                   .update(filename, 'utf8')
                   .digest('hex') + ext;
  var diskStream = fs.createWriteStream('./images/' + filename);
  file.pipe(diskStream).on('finish', function() {
    console.log('Finished writing file');
  });
});