【问题标题】:Getting always the same Hash with Node.js and Multer使用 Node.js 和 Multer 始终获得相同的 Hash
【发布时间】:2019-10-09 04:51:26
【问题描述】:

我尝试更改 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)
      })

【问题讨论】:

  • 您可能想改用crypto.randomBytes(64).toString("hex")。
  • 谢谢,但我实际上有点迷茫,我应该把它放在哪里?
  • 你抱怨 crypto.createHash('sha256') 返回相同的哈希值,对吧?
  • 当然,但是这样我会得到一个随机哈希,但是如果我想上传一个已经上传的文件(因为它是一个新版本),我应该得到相同的哈希
  • 你好,我有一些问题。请告诉我如何更换 DiskStorage?

标签: node.js hash md5 multer sha256


【解决方案1】:

在 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)
  })

...

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-06
    • 2020-10-21
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多