-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathindex.js
128 lines (110 loc) · 2.26 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
/**
* Module dependencies.
*/
var Emitter = require('emitter');
/**
* Expose `Upload`.
*/
module.exports = Upload;
/**
* Initialize a new `Upload` file`.
* This represents a single file upload.
*
* Events:
*
* - `error` an error occurred
* - `abort` upload was aborted
* - `progress` upload in progress (`e.percent` etc)
* - `end` upload is complete
*
* @param {File} file
* @api private
*/
function Upload(file) {
if (!(this instanceof Upload)) return new Upload(file);
Emitter.call(this);
this.file = file;
file.slice = file.slice || file.webkitSlice;
}
/**
* Mixin emitter.
*/
Emitter(Upload.prototype);
/**
* Upload to the given `path`.
*
* @param {String} options
* @param {Function} [fn]
* @api public
*/
Upload.prototype.to = function(options, fn){
// TODO: x-browser
var path;
if (typeof options == 'string') {
path = options;
options = {};
} else {
path = options.path;
}
var self = this;
fn = fn || function(){};
var req = this.req = new XMLHttpRequest;
req.open('POST', path);
req.onload = this.onload.bind(this);
req.onerror = this.onerror.bind(this);
req.upload.onprogress = this.onprogress.bind(this);
req.onreadystatechange = function(){
if (4 == req.readyState) {
var type = req.status / 100 | 0;
if (2 == type) return fn(null, req);
var err = new Error(req.statusText + ': ' + req.response);
err.status = req.status;
fn(err);
}
};
var key, headers = options.headers || {};
for (key in headers) {
req.setRequestHeader(key, headers[key]);
}
var body = new FormData;
body.append(options.name || 'file', this.file);
var data = options.data || {};
for (key in data) {
body.append(key, data[key]);
}
req.send(body);
};
/**
* Abort the XHR.
*
* @api public
*/
Upload.prototype.abort = function(){
this.emit('abort');
this.req.abort();
};
/**
* Error handler.
*
* @api private
*/
Upload.prototype.onerror = function(e){
this.emit('error', e);
};
/**
* Onload handler.
*
* @api private
*/
Upload.prototype.onload = function(e){
this.emit('end', this.req);
};
/**
* Progress handler.
*
* @api private
*/
Upload.prototype.onprogress = function(e){
e.percent = e.loaded / e.total * 100;
this.emit('progress', e);
};