Skip to content
Permalink
Browse files

create custom storage engine to get hash of file

  • Loading branch information...
tdjsnelling committed Jan 31, 2018
1 parent bb6f9b4 commit 5b2df52d18236974d1a6cc3db8c844490813800c
Showing with 75 additions and 1 deletion.
  1. +71 −0 customstorage.js
  2. +4 −1 index.js
@@ -0,0 +1,71 @@
var fs = require('fs');
var os = require('os');
var path = require('path');
var crypto = require('crypto');
var mkdirp = require('mkdirp');

function getFilename (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
cb(err, err ? undefined : raw.toString('hex'));
});
}

function getDestination (req, file, cb) {
cb(null, os.tmpdir());
}

function customStorage (opts) {
this.getFilename = (opts.filename || getFilename);

if (typeof opts.destination === 'string') {
mkdirp.sync(opts.destination);
this.getDestination = function ($0, $1, cb) { cb(null, opts.destination) };
} else {
this.getDestination = (opts.destination || getDestination);
}
}

customStorage.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);
file.stream.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')
});
});
});
});
}

customStorage.prototype._removeFile = function _removeFile (req, file, cb) {
var path = file.path;

delete file.destination;
delete file.filename;
delete file.path;

fs.unlink(path, cb);
}

module.exports = function (opts) {
return new customStorage(opts);
}
@@ -10,6 +10,7 @@ var consolidate = require('consolidate');
var useragent = require('express-useragent');
var mongoose = require('mongoose');

var customstorage = require('./customstorage');
var config = require('./config');

var port = config.port;
@@ -26,10 +27,11 @@ var uploadRecord = mongoose.model('upload', {
ip: String,
originalFilename: String,
filename: String,
hash: String,
timestamp: Number
});

var storage = multer.diskStorage({
var storage = customstorage({
destination: function (req, file, cb) {
cb(null, uploadPath)
},
@@ -93,6 +95,7 @@ app.post('/', (req, res) => {
ip: ip,
originalFilename: req.file.originalname,
filename: req.file.filename,
hash: req.file.hash,
timestamp: + new Date()
});

0 comments on commit 5b2df52

Please sign in to comment.
You can’t perform that action at this time.