forked from odysseyscience/react-s3-uploader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
s3upload.js
191 lines (172 loc) · 6.6 KB
/
s3upload.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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/**
* Taken, CommonJS-ified, and heavily modified from:
* https://github.com/flyingsparx/NodeDirectUploader
*/
S3Upload.prototype.server = '';
S3Upload.prototype.signingUrl = '/sign-s3';
S3Upload.prototype.signingUrlMethod = 'GET';
S3Upload.prototype.successResponses = [200, 201];
S3Upload.prototype.fileElement = null;
S3Upload.prototype.files = null;
S3Upload.prototype.onFinishS3Put = function(signResult, file) {
return console.log('base.onFinishS3Put()', signResult.publicUrl);
};
S3Upload.prototype.preprocess = function(file, next) {
return next(file);
};
S3Upload.prototype.onProgress = function(percent, status, file) {
return console.log('base.onProgress()', percent, status);
};
S3Upload.prototype.onError = function(status, file) {
return console.log('base.onError()', status);
};
S3Upload.prototype.onSignedUrl = function(result) {};
S3Upload.prototype.scrubFilename = function(filename) {
return filename.replace(/[^\w\d_\-\.]+/ig, '');
};
function S3Upload(options) {
if (options == null) {
options = {};
}
for (var option in options) {
if (options.hasOwnProperty(option)) {
this[option] = options[option];
}
}
var files = this.fileElement ? this.fileElement.files : this.files || [];
this.handleFileSelect(files);
}
S3Upload.prototype.handleFileSelect = function(files) {
var result = [];
for (var i=0; i < files.length; i++) {
var file = files[i];
this.preprocess(file, function(processedFile){
this.onProgress(0, 'Waiting', processedFile);
result.push(this.uploadFile(processedFile));
return result;
}.bind(this));
}
};
S3Upload.prototype.createCORSRequest = function(method, url, opts) {
var opts = opts || {};
var xhr = new XMLHttpRequest();
if (xhr.withCredentials != null) {
xhr.open(method, url, true);
if (opts.withCredentials != null) {
xhr.withCredentials = opts.withCredentials;
}
}
else if (typeof XDomainRequest !== "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
}
else {
xhr = null;
}
return xhr;
};
S3Upload.prototype.executeOnSignedUrl = function(file, callback) {
var fileName = this.scrubFilename(file.name);
var queryString = '?objectName=' + fileName + '&contentType=' + encodeURIComponent(file.type);
if (this.s3path) {
queryString += '&path=' + encodeURIComponent(this.s3path);
}
if (this.signingUrlQueryParams) {
var signingUrlQueryParams = typeof this.signingUrlQueryParams === 'function' ? this.signingUrlQueryParams() : this.signingUrlQueryParams;
Object.keys(signingUrlQueryParams).forEach(function(key) {
var val = signingUrlQueryParams[key];
queryString += '&' + key + '=' + val;
});
}
var xhr = this.createCORSRequest(this.signingUrlMethod,
this.server + this.signingUrl + queryString, { withCredentials: this.signingUrlWithCredentials });
if (this.signingUrlHeaders) {
var signingUrlHeaders = typeof this.signingUrlHeaders === 'function' ? this.signingUrlHeaders() : this.signingUrlHeaders;
Object.keys(signingUrlHeaders).forEach(function(key) {
var val = signingUrlHeaders[key];
xhr.setRequestHeader(key, val);
});
}
xhr.overrideMimeType && xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && this.successResponses.indexOf(xhr.status) >= 0) {
var result;
try {
result = JSON.parse(xhr.responseText);
this.onSignedUrl( result );
} catch (error) {
this.onError('Invalid response from server', file);
return false;
}
return callback(result);
} else if (xhr.readyState === 4 && this.successResponses.indexOf(xhr.status) < 0) {
return this.onError('Could not contact request signing server. Status = ' + xhr.status, file);
}
}.bind(this);
return xhr.send();
};
S3Upload.prototype.uploadToS3 = function(file, signResult) {
var xhr = this.createCORSRequest('PUT', signResult.signedUrl);
if (!xhr) {
this.onError('CORS not supported', file);
} else {
xhr.onload = function() {
if (this.successResponses.indexOf(xhr.status) >= 0) {
this.onProgress(100, 'Upload completed', file);
return this.onFinishS3Put(signResult, file);
} else {
return this.onError('Upload error: ' + xhr.status, file);
}
}.bind(this);
xhr.onerror = function() {
return this.onError('XHR error', file);
}.bind(this);
xhr.upload.onprogress = function(e) {
var percentLoaded;
if (e.lengthComputable) {
percentLoaded = Math.round((e.loaded / e.total) * 100);
return this.onProgress(percentLoaded, percentLoaded === 100 ? 'Finalizing' : 'Uploading', file);
}
}.bind(this);
}
xhr.setRequestHeader('Content-Type', file.type);
if (this.contentDisposition) {
var disposition = this.contentDisposition;
if (disposition === 'auto') {
if (file.type.substr(0, 6) === 'image/') {
disposition = 'inline';
} else {
disposition = 'attachment';
}
}
var fileName = this.scrubFilename(file.name)
xhr.setRequestHeader('Content-Disposition', disposition + '; filename="' + fileName + '"');
}
if (signResult.headers) {
var signResultHeaders = signResult.headers
Object.keys(signResultHeaders).forEach(function(key) {
var val = signResultHeaders[key];
xhr.setRequestHeader(key, val);
})
}
if (this.uploadRequestHeaders) {
var uploadRequestHeaders = this.uploadRequestHeaders;
Object.keys(uploadRequestHeaders).forEach(function(key) {
var val = uploadRequestHeaders[key];
xhr.setRequestHeader(key, val);
});
} else {
xhr.setRequestHeader('x-amz-acl', 'public-read');
}
this.httprequest = xhr;
return xhr.send(file);
};
S3Upload.prototype.uploadFile = function(file) {
var uploadToS3Callback = this.uploadToS3.bind(this, file);
if(this.getSignedUrl) return this.getSignedUrl(file, uploadToS3Callback);
return this.executeOnSignedUrl(file, uploadToS3Callback);
};
S3Upload.prototype.abortUpload = function() {
this.httprequest && this.httprequest.abort();
};
module.exports = S3Upload;