使用Node.js和Multer始终获得相同的哈希

时间:2019-05-22 16:23:37

标签: node.js hash md5 multer sha256

我试图更改multer / storage / disk.js文件,以便每次上传文件时都可以存储哈希,但是事实是,即使上传不同的文件,我也总是得到相同的哈希。

这就是我所做的。

DiskStorage.prototype._handleFile = function _handleFile (req, file, cb) {

  var that = this
  var hash = crypto.createHash('sha256')

  that.getDestination(req, file, function (err, destination) {
    if (err) return cb(err)

    that.getFilename(req, file, function (err, filename) {
      if (err) return cb(err)

      var finalPath = path.join(destination, filename)
      var outStream = fs.createWriteStream(finalPath)

      file.stream.pipe(outStream)
      outStream.on('error', cb)
      outStream.on('data', function (chunk) {
        hash.update(chunk)
      })

      outStream.on('finish', function () {
        cb(null, {
          destination: destination,
          filename: filename,
          path: finalPath,
          size: outStream.bytesWritten,
          hash: hash.digest('hex')

        })
      })
    })
  })
}

就像本节没有做任何事情

outStream.on('data', function (chunk) {
        hash.update(chunk)
      })

1 个答案:

答案 0 :(得分:0)

在Multers github中有一个关于此问题的讨论: https://github.com/expressjs/multer/issues/248

microacup发布了有关suhaotion的代码(看起来像您的代码)的信息

DiskStorage.prototype._handleFile = function _handleFile (req, file, cb) {
...
  file.stream.on('data', function (chunk) {
      hash.update(chunk)
  })

...

代替

DiskStorage.prototype._handleFile = function _handleFile (req, file, cb) {
...
  outStream.on('data', function (chunk) {
      hash.update(chunk)
  })

...