forked from OriginalEXE/Multer-Storage-S3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
148 lines (92 loc) · 2.36 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
var path = require( 'path' );
var crypto = require( 'crypto' );
var mime = require( 'mime-types' );
var AWS = require( 'aws-sdk' );
function getFilename( req, file, cb ) {
var ext = path.extname(file.originalname);
crypto.pseudoRandomBytes( 16, function ( err, raw ) {
cb( err, err ? undefined : raw.toString( 'hex' ) + ext );
});
}
function getDestination( req, file, cb ) {
cb( null, '' );
}
function S3Storage( opts ) {
this.getFilename = ( opts.filename || getFilename );
if ( 'string' === typeof opts.destination ) {
this.getDestination = function( $0, $1, cb ) { cb( null, opts.destination ); }
} else {
this.getDestination = ( opts.destination || getDestination );
}
if (!opts.aws) {
throw new Error( 'You have to specify aws for S3 Storage to work.' );
}
if (!opts.bucket) {
throw new Error( 'You have to specify bucket for S3 Storage to work.' );
}
AWS.config.update(opts.aws);
this.s3obj = new AWS.S3({
params: {
Bucket: opts.bucket
}
});
this.options = opts;
}
S3Storage.prototype._handleFile = function _handleFile( req, file, cb ) {
var self = this
self.getDestination( req, file, function( err, destination ) {
if ( err ) {
return cb( err );
}
self.getFilename( req, file, function( err, filename ) {
if ( err ) {
return cb( err );
}
var finalPath = path.join( destination, filename ),
size,
contentType = mime.lookup( finalPath ),
params = {
Key : finalPath,
Body: file.stream
};
if ( contentType ) {
params.ContentType = contentType;
}
if (self.options.ACL) {
params.ACL = self.options.ACL;
}
self.s3obj
.upload( params )
.on( 'httpUploadProgress', function( info ){
if ( info.total ) {
size = info.total;
}
})
.send( function( err, data ) {
if ( err ) {
cb( err, data );
} else {
cb( null, {
destination: destination,
filename : filename,
path : finalPath,
size : size,
s3 : {
ETag : data.ETag,
Location: data.Location
}
});
}
});
});
});
};
S3Storage.prototype._removeFile = function _removeFile( req, file, cb ) {
this.s3obj.deleteObject({
Bucket: this.options.bucket,
Key : file.path
}, cb );
};
module.exports = function( opts ) {
return new S3Storage( opts );
};