| 29 | } |
| 30 | |
| 31 | export default function upload(option) { |
| 32 | if (typeof XMLHttpRequest === 'undefined') { |
| 33 | return; |
| 34 | } |
| 35 | |
| 36 | const xhr = new XMLHttpRequest(); |
| 37 | const action = option.action; |
| 38 | |
| 39 | if (xhr.upload) { |
| 40 | xhr.upload.onprogress = function progress(e) { |
| 41 | if (e.total > 0) { |
| 42 | e.percent = e.loaded / e.total * 100; |
| 43 | } |
| 44 | option.onProgress(e); |
| 45 | }; |
| 46 | } |
| 47 | |
| 48 | const formData = new FormData(); |
| 49 | |
| 50 | if (option.data) { |
| 51 | Object.keys(option.data).map(key => { |
| 52 | formData.append(key, option.data[key]); |
| 53 | }); |
| 54 | } |
| 55 | |
| 56 | formData.append(option.filename, option.file); |
| 57 | |
| 58 | xhr.onerror = function error(e) { |
| 59 | option.onError(e); |
| 60 | }; |
| 61 | |
| 62 | xhr.onload = function onload() { |
| 63 | if (xhr.status < 200 || xhr.status >= 300) { |
| 64 | return option.onError(getError(action, option, xhr)); |
| 65 | } |
| 66 | |
| 67 | option.onSuccess(getBody(xhr)); |
| 68 | }; |
| 69 | |
| 70 | xhr.open('post', action, true); |
| 71 | |
| 72 | if (option.withCredentials && 'withCredentials' in xhr) { |
| 73 | xhr.withCredentials = true; |
| 74 | } |
| 75 | |
| 76 | const headers = option.headers || {}; |
| 77 | |
| 78 | for (let item in headers) { |
| 79 | if (headers.hasOwnProperty(item) && headers[item] !== null) { |
| 80 | xhr.setRequestHeader(item, headers[item]); |
| 81 | } |
| 82 | } |
| 83 | xhr.send(formData); |
| 84 | return xhr; |
| 85 | } |