Skip to content

Instantly share code, notes, and snippets.

@JotaroX
Created March 19, 2016 15:19
Show Gist options
  • Save JotaroX/3542513f75b362abf5b6 to your computer and use it in GitHub Desktop.
Save JotaroX/3542513f75b362abf5b6 to your computer and use it in GitHub Desktop.
Node.js multer upload dynamic folder support jQuery file upload
var moment = require('moment'),
path = require('path'),
crypto = require('crypto'),
multer = require('multer');
module.exports = function (app) {
app.post('/upload', multer({
storage: multer.diskStorage({
destination: path.join(__dirname, '../upload/media', moment().format('YYYY/MM/DD')),
filename: function (req, file, cb) {
crypto.pseudoRandomBytes(16, function (err, raw) {
if (err) return cb(err)
cb(null, raw.toString('hex') + path.extname(file.originalname).toLowerCase());
})
}
})
}).any(), function (req, res) {
console.log(req.files);
var _files = req.files;
if (_files) {
var _root = path.join(__dirname, '../upload');
_files.forEach(function (f) {
f.path = f.path.replace(_root, '');
f.url = 'http://'+ req.hostname + f.path;
});
return res.jsonp({files: _files});
}
return res.jsonp({
msg: 'Invalid upload'
});
});
return app;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment