2020-12-23 11:49:00 +00:00
|
|
|
class Upload {
|
|
|
|
constructor() {
|
|
|
|
this.xhr = new XMLHttpRequest();
|
|
|
|
this.formData = new FormData();
|
|
|
|
}
|
|
|
|
|
|
|
|
then = (callback) => {
|
|
|
|
this.xhr.onload = () => callback({ respInfo: this.xhr });
|
|
|
|
this.xhr.send(this.formData);
|
|
|
|
}
|
|
|
|
|
|
|
|
catch = (callback) => {
|
|
|
|
this.xhr.onerror = callback;
|
|
|
|
}
|
2020-12-01 20:19:48 +00:00
|
|
|
|
2020-12-23 11:49:00 +00:00
|
|
|
uploadProgress = (callback) => {
|
|
|
|
this.xhr.upload.onprogress = ({ total, loaded }) => callback(loaded, total);
|
|
|
|
}
|
|
|
|
|
|
|
|
cancel = () => {
|
|
|
|
this.xhr.abort();
|
|
|
|
return Promise.resolve();
|
|
|
|
}
|
|
|
|
}
|
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
|
|
|
|
|
|
|
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
|
|
|
});
|
|
|
|
|
|
|
|
data.forEach((item) => {
|
|
|
|
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;
|
2020-12-01 20:19:48 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const fileUpload = new FileUpload();
|
|
|
|
export default fileUpload;
|