UNPKG

2.52 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, "__esModule", {
4 value: true
5});
6exports["default"] = upload;
7/**
8* This source code is quoted from rc-upload.
9* homepage: https://github.com/react-component/upload
10*/
11function getError(option, xhr) {
12 var msg = 'cannot post ' + option.action + ' ' + xhr.status + '\'';
13 var err = new Error(msg);
14 err.status = xhr.status;
15 err.method = 'post';
16 err.url = option.action;
17 return err;
18}
19
20function getBody(xhr) {
21 var text = xhr.responseText || xhr.response;
22 if (!text) {
23 return text;
24 }
25
26 try {
27 return JSON.parse(text);
28 } catch (e) {
29 return text;
30 }
31}
32
33// option {
34// onProgress: (event: { percent: number }): void,
35// onError: (event: Error, body?: Object): void,
36// onSuccess: (body: Object): void,
37// data: Object,
38// filename: String,
39// file: File,
40// withCredentials: Boolean,
41// action: String,
42// headers: Object,
43// }
44function upload(option) {
45 var xhr = new XMLHttpRequest();
46 if (xhr.upload) {
47 xhr.upload.onprogress = function progress(e) {
48 if (e.total > 0) {
49 e.percent = e.loaded / e.total * 100;
50 }
51 option.onProgress(e);
52 };
53 }
54
55 var formData = new FormData();
56
57 if (option.data) {
58 Object.keys(option.data).map(function (key) {
59 formData.append(key, option.data[key]);
60 });
61 }
62
63 formData.append(option.filename, option.file);
64
65 xhr.onerror = function error(e) {
66 option.onError(e);
67 };
68
69 xhr.onload = function onload() {
70 // allow success when 2xx status
71 // see https://github.com/react-component/upload/issues/34
72 if (xhr.status < 200 || xhr.status >= 300) {
73 return option.onError(getError(option, xhr), getBody(xhr));
74 }
75
76 option.onSuccess(getBody(xhr));
77 };
78
79 xhr.open('post', option.action, true);
80
81 // Has to be after `.open()`. See https://github.com/enyo/dropzone/issues/179
82 if (option.withCredentials && 'withCredentials' in xhr) {
83 xhr.withCredentials = true;
84 }
85
86 var headers = option.headers || {};
87
88 // when set headers['X-Requested-With'] = null , can close default XHR header
89 // see https://github.com/react-component/upload/issues/33
90 if (headers['X-Requested-With'] !== null) {
91 xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
92 }
93
94 for (var h in headers) {
95 if (headers.hasOwnProperty(h) && headers[h] !== null) {
96 xhr.setRequestHeader(h, headers[h]);
97 }
98 }
99 xhr.send(formData);
100
101 return {
102 abort: function abort() {
103 xhr.abort();
104 }
105 };
106}
107module.exports = exports['default'];
\No newline at end of file