-
-
Notifications
You must be signed in to change notification settings - Fork 118
/
Copy pathfile.js
405 lines (334 loc) · 9.17 KB
/
file.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/* global atob, Uint8Array */
import { registerWaiter } from '@ember/test';
import { DEBUG } from '@glimmer/env';
import { assert } from '@ember/debug';
import EmberObject, { set, get, computed } from '@ember/object';
import FileReader from './system/file-reader';
import HTTPRequest from './system/http-request';
import RSVP from 'rsvp';
import uuid from './system/uuid';
const { reads } = computed;
function normalizeOptions(file, url, options) {
if (typeof url === 'object') {
options = url;
url = null;
}
options = options || {};
options.url = options.url || url;
options.method = options.method || 'POST';
options.accepts = options.accepts || ['application/json', 'text/javascript'];
if (!options.hasOwnProperty('contentType')) {
options.contentType = get(file, 'type');
}
options.headers = options.headers || {};
options.data = options.data || {};
options.fileKey = options.fileKey || 'file';
if (options.headers.Accept == null) {
if (!Array.isArray(options.accepts)) {
options.accepts = [options.accepts];
}
options.headers.Accept = options.accepts.join(',');
}
// Set Content-Type in the data payload
// instead of the headers, since the header
// for Content-Type will always be multipart/form-data
if (options.contentType) {
options.data['Content-Type'] = options.contentType;
}
options.data[options.fileKey] = file.blob;
options.withCredentials = options.withCredentials || false;
return options;
}
function upload(file, url, opts, uploadFn) {
if (['queued', 'failed', 'timed_out', 'aborted'].indexOf(get(file, 'state')) === -1) {
assert(`The file ${file.id} is in the state "${get(file, 'state')}" and cannot be requeued.`);
}
let options = normalizeOptions(file, url, opts);
let request = new HTTPRequest({
withCredentials: options.withCredentials,
label: `${options.method} ${get(file, 'name') } to ${options.url}`
});
request.open(options.method, options.url);
Object.keys(options.headers).forEach(function (key) {
request.setRequestHeader(key, options.headers[key]);
});
if (options.timeout) {
request.timeout = options.timeout;
}
request.onprogress = function (evt) {
if (evt.lengthComputable) {
set(file, 'loaded', evt.loaded);
set(file, 'size', evt.total);
set(file, 'progress', (evt.loaded / evt.total) * 100);
}
};
request.ontimeout = function () {
set(file, 'state', 'timed_out');
};
request.onabort = function () {
set(file, 'state', 'aborted');
};
set(file, 'state', 'uploading');
// Increment for Ember.Test
inflightRequests++;
let uploadPromise = uploadFn(request, options);
uploadPromise = uploadPromise.then(function (result) {
set(file, 'state', 'uploaded');
return result;
}, function (error) {
set(file, 'state', 'failed');
return RSVP.reject(error);
}).finally(function () {
// Decrement for Ember.Test
inflightRequests--;
});
return uploadPromise;
}
let inflightRequests = 0;
if (DEBUG) {
registerWaiter(null, function () {
return inflightRequests === 0;
});
}
/**
Files provide a uniform interface for interacting
with data that can be uploaded or read.
@class File
@extends Ember.Object
*/
export default EmberObject.extend({
init() {
this._super();
Object.defineProperty(this, 'id', {
writeable: false,
enumerable: true,
value: `file-${uuid()}`
});
},
/**
A unique id generated for this file.
@property id
@type {String}
@readonly
*/
id: null,
/**
The file name.
@accessor name
@type {String}
*/
name: computed({
get() {
return get(this, 'blob.name');
},
set(_, name) {
return name;
}
}),
/**
The size of the file in bytes.
@accessor size
@type {Number}
@readonly
*/
size: reads('blob.size'),
/**
The MIME type of the file.
For a image file this may be `image/png`.
@accessor type
@type {String}
@readonly
*/
type: reads('blob.type'),
/**
Returns the appropriate file extension of
the file according to the type
@accessor extension
@type {String}
@readonly
*/
extension: computed('type', {
get() {
return get(this, 'type').split('/').slice(-1)[0];
}
}),
/**
@accessor loaded
@type {Number}
@default 0
@readonly
*/
loaded: 0,
/**
@accessor progress
@type {Number}
@default 0
@readonly
*/
progress: 0,
/**
The current state that the file is in.
One of:
- `queued`
- `uploading`
- `timed_out`
- `aborted`
- `uploaded`
- `failed`
@accessor state
@type {String}
@default 'queued'
@readonly
*/
state: 'queued',
/**
The source of the file. This is useful
for applications that want to gather
analytics about how users upload their
content.
This property can be one of the following:
- `browse`
- `drag-and-drop`
- `web`
- `data-url`
- `blob`
`browse` is the source when the file is created
using the native file picker.
`drag-and-drop` is the source when the file was
created using drag and drop from their desktop.
`web` is the source when the file was created
by dragging the file from another webpage.
`data-url` is the source when the file is created
from a data URL using the `fromDataURL` method for
files. This usually means that the file was created
manually by the developer on behalf of the user.
`blob` is the source when the file is created
from a blob using the `fromBlob` method for
files. This usually means that the file was created
manually by the developer.
@accessor source
@type {String}
@default ''
@readonly
*/
source: '',
/**
* Upload file with `application/octet-stream` content type.
*
* @method uploadBinary
* @param {String} url Your server endpoint where to upload the file
* @param {hash} opts
* @return {Promise}
*/
uploadBinary(url, opts) {
opts.contentType = 'application/octet-stream';
return upload(this, url, opts, (request) => {
return request.send(get(this, 'blob'));
});
},
/**
* Upload file to your server
*
* @method upload
* @param {String} url Your server endpoint where to upload the file
* @param {Hash} opts { fileKey: string, data: { key: string } }
* @return {Promise}
*/
upload(url, opts) {
return upload(this, url, opts, (request, options) => {
// Build the form
let form = new FormData();
Object.keys(options.data).forEach((key) => {
if (key === options.fileKey) {
form.append(key, options.data[key], get(this, 'name'));
} else {
form.append(key, options.data[key]);
}
});
return request.send(form);
});
},
/**
* Resolves with Blob as ArrayBuffer
*
* @method readAsArrayBuffer
* @return {Promise}
*/
readAsArrayBuffer() {
let reader = new FileReader({ label: `Read ${get(this, 'name')} as an ArrayBuffer` });
return reader.readAsArrayBuffer(this.blob);
},
/**
* Resolves with Blob as DataURL
*
* @method readAsDataURL
* @return {Promise}
*/
readAsDataURL() {
let reader = new FileReader({ label: `Read ${get(this, 'name')} as a Data URI` });
return reader.readAsDataURL(this.blob);
},
/**
* Resolves with Blob as binary string
*
* @method readAsBinaryString
* @return {Promise}
*/
readAsBinaryString() {
let reader = new FileReader({ label: `Read ${get(this, 'name')} as a binary string` });
return reader.readAsBinaryString(this.blob);
},
/**
* Resolves with Blob as plain text
*
* @method readAsText
* @return {Promise}
*/
readAsText() {
let reader = new FileReader({ label: `Read ${get(this, 'name')} as text` });
return reader.readAsText(this.blob);
}
}).reopenClass({
/**
Creates a file object that can be read or uploaded to a
server from a Blob object.
@static
@method fromBlob
@param {Blob} blob The blob to create the file from.
@param {String} [source] The source that created the blob.
@return {File} A file object
*/
fromBlob(blob, source='blob') {
let file = this.create();
Object.defineProperty(file, 'blob', {
writeable: false,
enumerable: false,
value: blob
});
Object.defineProperty(file, 'source', {
writeable: false,
value: source
});
return file;
},
/**
Creates a file object that can be read or uploaded to a
server from a data URL.
@static
@method fromDataURL
@param {String} dataURL The data URL to create the file from.
@param {String} [source] The source of the data URL.
@return {File} A file object
*/
fromDataURL(dataURL, source='data-url') {
let [typeInfo, base64String] = dataURL.split(',');
let mimeType = typeInfo.match(/:(.*?);/)[1];
let binaryString = atob(base64String);
let binaryData = new Uint8Array(binaryString.length);
for (let i = 0, len = binaryString.length; i < len; i++) {
binaryData[i] = binaryString.charCodeAt(i);
}
let blob = new Blob([binaryData], { type: mimeType });
return this.fromBlob(blob, source);
}
});