Skip to content

Instantly share code, notes, and snippets.

@julianpoemp
Last active February 11, 2022 09:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julianpoemp/302727bc46a8761f1206c5639bca25cf to your computer and use it in GitHub Desktop.
Save julianpoemp/302727bc46a8761f1206c5639bca25cf to your computer and use it in GitHub Desktop.
How to hash files while uploading using multer and typescript. Keywords: nodejs, expressjs, multer, upload, hashing

How to hash files while uploading using multer and typescript

  1. Copy the file 'multer-storage-hashing.ts' to your development directory.
  2. Import the file in your typescript of choice.
  3. Now you can initialize the multer storage:

Example:

const storage = new MulterStorageHashing({
      // ... optional storage options 
    });
const upload = multer({storage: storage});
import * as fs from "fs";
import {DiskStorageOptions, StorageEngine} from "multer";
import * as Path from "path";
import * as os from "os";
import {mkdirpSync} from "fs-extra";
import * as crypto from "crypto";
export class MulterStorageHashing implements StorageEngine {
getFilename(req, file, cb) {
crypto.randomBytes(16, function (err, raw) {
cb(err, err ? undefined : raw.toString('hex'))
})
}
getDestination(req, file, cb) {
cb(null, os.tmpdir())
};
constructor(opts: DiskStorageOptions) {
this.getFilename = (opts.filename || this.getFilename)
if (typeof opts.destination === 'string') {
mkdirpSync(opts.destination);
this.getDestination = ($0, $1, cb) => {
cb(null, opts.destination)
}
} else {
this.getDestination = (opts.destination || this.getDestination)
}
}
_handleFile(req, file, cb) {
this.getDestination(req, file, (err, destination) => {
if (err) return cb(err)
this.getFilename(req, file, (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);
const hash = crypto.createHash('sha256')
file.stream.on('data', function (chunk) {
hash.update(chunk)
});
outStream.on('finish', () => {
cb(null, {
destination: destination,
filename: filename,
path: finalPath,
size: outStream.bytesWritten,
hash: hash.digest('hex')
})
})
})
});
}
_removeFile(req, file, cb) {
var path = file.path
delete file.destination
delete file.filename
delete file.path
fs.unlink(path, cb)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment