-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathoss-js-upload.js
336 lines (282 loc) · 8.49 KB
/
oss-js-upload.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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
'use strict';
(function () {
var detectIEVersion = function () {
var v = 4,
div = document.createElement('div'),
all = div.getElementsByTagName('i');
while (
div.innerHTML = '<!--[if gt IE ' + v + ']><i></i><![endif]-->',
all[0]
) {
v++;
}
return v > 4 ? v : false;
};
var _extend = function (dst, src) {
for (var i in src) {
if (Object.prototype.hasOwnProperty.call(src, i) && src[i]) {
dst[i] = src[i];
}
}
};
function OssUpload(config) {
if (!config) {
// console.log('需要 config');
return;
}
this._config = {
chunkSize: 1048576 // 1MB
};
if (this._config.chunkSize && this._config.chunkSize < 102400) {
// console.log('chunkSize 不能小于 100KB');
return;
}
_extend(this._config, config);
if (!this._config.aliyunCredential && !this._config.stsToken) {
// console.log('需要 stsToken');
return;
}
if (!this._config.endpoint) {
// console.log('需要 endpoint');
return;
}
var ALY = window.ALY;
if (this._config.stsToken) {
this.oss = new ALY.OSS({
accessKeyId: this._config.stsToken.Credentials.AccessKeyId,
secretAccessKey: this._config.stsToken.Credentials.AccessKeySecret,
securityToken: this._config.stsToken.Credentials.SecurityToken,
endpoint: this._config.endpoint,
apiVersion: '2013-10-15'
});
}
else {
this.oss = new ALY.OSS({
accessKeyId: this._config.aliyunCredential.accessKeyId,
secretAccessKey: this._config.aliyunCredential.secretAccessKey,
endpoint: this._config.endpoint,
apiVersion: '2013-10-15'
});
}
var arr = this._config.endpoint.split('://');
if (arr.length < 2) {
// console.log('endpoint 格式错误');
return;
}
this._config.endpoint = {
protocol: arr[0],
host: arr[1]
}
}
OssUpload.prototype.upload = function (options) {
if (!options) {
if (typeof options.onerror == 'function') {
options.onerror('需要 options');
}
return;
}
if (!options.file) {
if (typeof options.onerror == 'function') {
options.onerror('需要 file');
}
return;
}
var file = options.file;
if (!options.key) {
if (typeof options.onerror == 'function') {
options.onerror('需要 key');
}
return;
}
// 去掉 key 开头的 /
options.key.replace(new RegExp("^\/"), '');
var self = this;
var readFile = function (callback) {
var result = {
chunksHash: {},
chunks: []
};
var blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
var chunkSize = self._config.chunkSize;
var chunksNum = Math.ceil(file.size / chunkSize);
var currentChunk = 0;
var frOnload = function (e) {
result.chunks[currentChunk] = e.target.result;
currentChunk++;
if (currentChunk < chunksNum) {
loadNext();
}
else {
result.file_size = file.size;
callback(null, result);
}
};
var frOnerror = function () {
console.error("读取文件失败");
if (typeof options.onerror == 'function') {
options.onerror("读取文件失败");
}
};
function loadNext() {
var fileReader = new FileReader();
fileReader.onload = frOnload;
fileReader.onerror = frOnerror;
var start = currentChunk * chunkSize,
end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
var blobPacket = blobSlice.call(file, start, end);
fileReader.readAsArrayBuffer(blobPacket);
}
loadNext();
};
var uploadSingle = function (result, callback) {
var params = {
Bucket: self._config.bucket,
Key: options.key,
Body: result.chunks[0],
ContentType: file.type || ''
};
_extend(params, options.headers);
var req = self.oss.putObject(params, callback);
req.on('httpUploadProgress', function(p) {
if (typeof options.onprogress == 'function') {
options.onprogress({
loaded: p.loaded,
total: file.size
});
}
});
};
var uploadMultipart = function (result, callback) {
var maxUploadTries = options.maxRetry || 3;
var uploadId;
var loadedNum = 0;
var latestUploadNum = -1;
var concurrency = 0;
var multipartMap = {
Parts: []
};
var init = function () {
var params = {
Bucket: self._config.bucket,
Key: options.key,
ContentType: file.type || ''
};
_extend(params, options.headers);
self.oss.createMultipartUpload(params,
function (mpErr, res) {
if (mpErr) {
// console.log('Error!', mpErr);
callback(mpErr);
return;
}
// console.log("Got upload ID", res.UploadId);
uploadId = res.UploadId;
uploadPart(0);
});
};
var uploadPart = function (partNum) {
if(partNum >= result.chunks.length) {
return;
}
concurrency++;
if(latestUploadNum < partNum) {
latestUploadNum = partNum;
}
if(concurrency < self._config.concurrency && (partNum < (result.chunks.length - 1))) {
uploadPart(partNum + 1);
}
var partParams = {
Body: result.chunks[partNum],
Bucket: self._config.bucket,
Key: options.key,
PartNumber: String(partNum + 1),
UploadId: uploadId
};
var tryNum = 1;
var doUpload = function () {
multipartMap.Parts[partNum] = {
PartNumber: partNum + 1,
loaded: 0
};
var req = self.oss.uploadPart(partParams, function (multiErr, mData) {
if (multiErr) {
// console.log('multiErr, upload part error:', multiErr);
if (tryNum > maxUploadTries) {
console.log('上传分片失败: #', partParams.PartNumber);
callback(multiErr);
}
else {
console.log('重新上传分片: #', partParams.PartNumber);
multipartMap.Parts[partNum].loaded = 0;
tryNum++;
doUpload();
}
return;
}
multipartMap.Parts[partNum].ETag = mData.ETag;
multipartMap.Parts[partNum].loaded = partParams.Body.byteLength;
// console.log(mData);
concurrency--;
console.log("Completed part", partNum + 1);
//console.log('mData', mData);
loadedNum++;
if (loadedNum == result.chunks.length) {
complete();
}
else {
uploadPart(latestUploadNum + 1);
}
});
req.on('httpUploadProgress', function(p) {
multipartMap.Parts[partNum].loaded = p.loaded;
var loaded = 0;
for(var i in multipartMap.Parts) {
loaded += multipartMap.Parts[i].loaded;
}
if (typeof options.onprogress == 'function') {
options.onprogress({
loaded: loaded,
total: file.size
});
}
});
};
doUpload();
};
var complete = function () {
// console.log("Completing upload...");
for(var i in multipartMap.Parts) {
delete multipartMap.Parts[i].loaded;
}
var doneParams = {
Bucket: self._config.bucket,
Key: options.key,
CompleteMultipartUpload: multipartMap,
UploadId: uploadId
};
self.oss.completeMultipartUpload(doneParams, callback);
};
init();
};
readFile(function (err, result) {
var callback = function (err, res) {
if (err) {
if (typeof options.onerror == 'function') {
options.onerror(err);
}
return;
}
if (typeof options.oncomplete == 'function') {
options.oncomplete(res);
}
};
if (result.chunks.length == 1) {
uploadSingle(result, callback)
}
else {
uploadMultipart(result, callback);
}
});
};
window.OssUpload = OssUpload;
})();