1 | var fs = require('fs')
|
2 | var os = require('os')
|
3 | var path = require('path')
|
4 | var crypto = require('crypto')
|
5 | var mkdirp = require('mkdirp')
|
6 |
|
7 | function getFilename (req, file, cb) {
|
8 | crypto.pseudoRandomBytes(16, function (err, raw) {
|
9 | cb(err, err ? undefined : raw.toString('hex'))
|
10 | })
|
11 | }
|
12 |
|
13 | function getDestination (req, file, cb) {
|
14 | cb(null, os.tmpdir())
|
15 | }
|
16 |
|
17 | function DiskStorage (opts) {
|
18 | this.getFilename = (opts.filename || getFilename)
|
19 |
|
20 | if (typeof opts.destination === 'string') {
|
21 | mkdirp.sync(opts.destination)
|
22 | this.getDestination = function ($0, $1, cb) { cb(null, opts.destination) }
|
23 | } else {
|
24 | this.getDestination = (opts.destination || getDestination)
|
25 | }
|
26 | }
|
27 |
|
28 | DiskStorage.prototype._handleFile = function _handleFile (req, file, cb) {
|
29 | var that = this
|
30 |
|
31 | that.getDestination(req, file, function (err, destination) {
|
32 | if (err) return cb(err)
|
33 |
|
34 | that.getFilename(req, file, function (err, filename) {
|
35 | if (err) return cb(err)
|
36 |
|
37 | var finalPath = path.join(destination, filename)
|
38 | var outStream = fs.createWriteStream(finalPath)
|
39 |
|
40 | file.stream.pipe(outStream)
|
41 | outStream.on('error', cb)
|
42 | outStream.on('finish', function () {
|
43 | cb(null, {
|
44 | destination: destination,
|
45 | filename: filename,
|
46 | path: finalPath,
|
47 | size: outStream.bytesWritten
|
48 | })
|
49 | })
|
50 | })
|
51 | })
|
52 | }
|
53 |
|
54 | DiskStorage.prototype._removeFile = function _removeFile (req, file, cb) {
|
55 | var path = file.path
|
56 |
|
57 | delete file.destination
|
58 | delete file.filename
|
59 | delete file.path
|
60 |
|
61 | fs.unlink(path, cb)
|
62 | }
|
63 |
|
64 | module.exports = function (opts) {
|
65 | return new DiskStorage(opts)
|
66 | }
|