export interface ProgressCallback {
(progress: number): void;
}
type UploadParams<T extends Record<string, any> = Record<string, any>> = T & {
file: File;
};
// json格式转换为 formdata格式
const formdataify = (params: Record<string, any>) => {
const formData = new FormData();
Object.keys(params).forEach((key) => {
formData.append(key, params[key]);
});
return formData;
};
/**
* 上传,可获取到上传进度
* url 上传地址
* params 上传参数,传入 json 格式 使用 formdataify 自动转成 formdata
* onProgress 上传进度
*/
export class FileUploader {
uploadFile(
url: string,
params: UploadParams,
onProgress?: ProgressCallback
): Promise<Record<string, any>> {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", (event: ProgressEvent) => {
if (event.lengthComputable) {
const progress = Math.round((event.loaded / event.total) * 100);
if (typeof onProgress === "function") {
onProgress(progress);
}
}
});
xhr.addEventListener("load", () => {
if (xhr.status === 200 || xhr.status === 201) {
resolve(JSON.parse(xhr.responseText));
} else {
reject(JSON.parse(xhr.responseText));
}
});
xhr.addEventListener("error", () => {
reject(JSON.parse(xhr.responseText));
});
xhr.open("POST", url);
xhr.send(formdataify(params));
});
}
}
在
network
里面调一下速度限制测试看看,打印出你的progress
看看