2020-12-23 11:49:00 +00:00
|
|
|
class Upload {
|
|
|
|
constructor() {
|
|
|
|
this.xhr = new XMLHttpRequest();
|
|
|
|
this.formData = new FormData();
|
|
|
|
}
|
|
|
|
|
2021-09-13 20:41:05 +00:00
|
|
|
then = callback => {
|
2020-12-23 11:49:00 +00:00
|
|
|
this.xhr.onload = () => callback({ respInfo: this.xhr });
|
|
|
|
this.xhr.send(this.formData);
|
2021-09-13 20:41:05 +00:00
|
|
|
};
|
2020-12-23 11:49:00 +00:00
|
|
|
|
2021-09-13 20:41:05 +00:00
|
|
|
catch = callback => {
|
2020-12-23 11:49:00 +00:00
|
|
|
this.xhr.onerror = callback;
|
2021-09-13 20:41:05 +00:00
|
|
|
};
|
2020-12-01 20:19:48 +00:00
|
|
|
|
2021-09-13 20:41:05 +00:00
|
|
|
uploadProgress = callback => {
|
2020-12-23 11:49:00 +00:00
|
|
|
this.xhr.upload.onprogress = ({ total, loaded }) => callback(loaded, total);
|
2021-09-13 20:41:05 +00:00
|
|
|
};
|
2020-12-23 11:49:00 +00:00
|
|
|
|
|
|
|
cancel = () => {
|
|
|
|
this.xhr.abort();
|
|
|
|
return Promise.resolve();
|
2021-09-13 20:41:05 +00:00
|
|
|
};
|
2020-12-23 11:49:00 +00:00
|
|
|
}
|
2020-12-01 20:19:48 +00:00
|
|
|
|
2020-12-23 11:49:00 +00:00
|
|
|
class FileUpload {
|
2020-12-01 20:19:48 +00:00
|
|
|
fetch = (method, url, headers, data) => {
|
2020-12-23 11:49:00 +00:00
|
|
|
const upload = new Upload();
|
|
|
|
upload.xhr.open(method, url);
|
2020-12-01 20:19:48 +00:00
|
|
|
|
2021-09-13 20:41:05 +00:00
|
|
|
Object.keys(headers).forEach(key => {
|
2020-12-23 11:49:00 +00:00
|
|
|
upload.xhr.setRequestHeader(key, headers[key]);
|
2020-12-01 20:19:48 +00:00
|
|
|
});
|
|
|
|
|
2021-09-13 20:41:05 +00:00
|
|
|
data.forEach(item => {
|
2020-12-01 20:19:48 +00:00
|
|
|
if (item.uri) {
|
2020-12-23 11:49:00 +00:00
|
|
|
upload.formData.append(item.name, {
|
2020-12-01 20:19:48 +00:00
|
|
|
uri: item.uri,
|
|
|
|
type: item.type,
|
|
|
|
name: item.filename
|
|
|
|
});
|
|
|
|
} else {
|
2020-12-23 11:49:00 +00:00
|
|
|
upload.formData.append(item.name, item.data);
|
2020-12-01 20:19:48 +00:00
|
|
|
}
|
|
|
|
});
|
|
|
|
|
2020-12-23 11:49:00 +00:00
|
|
|
return upload;
|
2021-09-13 20:41:05 +00:00
|
|
|
};
|
2020-12-01 20:19:48 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const fileUpload = new FileUpload();
|
|
|
|
export default fileUpload;
|