上传进度,为啥 onProgress 方法直接 100%,并不是 1,2,3....?

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));
    });
  }
}
阅读 2.3k
1 个回答

network里面调一下速度限制测试看看,打印出你的progress看看

image.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Microsoft
子站问答
访问
宣传栏