首页 > 解决方案 > Axios onUploadProgress 在服务器实际发送响应之前立即返回 1

问题描述

当用户将数据发送到服务器时,我正在尝试在我的本机应用程序中实现进度条。我正在尝试使用 axios 中的 onUploadProgress 选项来获取发布请求的进度并将其映射到本机反应的 Progress.Bar 组件。onUploadProgress 没有获得持续的进度更新,而是立即返回 1(表示上传完成),但实际上直到几分钟后我才真正得到服务器的响应。这会导致进度条立即填满,这显然会让用户感到困惑,因为响应尚未完成。我用谷歌搜索了这个并找到了关于这个问题的类似线程和帖子,但我似乎找不到解决方案。这是我的代码的样子:

//Post request to server...
const uploadVideo = async (id, uri, onUploadProgress) => {
  const formData = new FormData();
  formData.append("video", {
    name: uri,
    type: "video/mp4",
    uri,
  });
  const result = await axios.post(`${endpoint}/${id}/videos`, formData, {
    headers: {
      "Content-type": "multipart/form-data",
    },
    onUploadProgress: function (progress) {
      onUploadProgress(progress.loaded / progress.total);
    },
  });
  return result;
};

//Function inside component that calls the POST function...
//media.uri comes from the user selecting a video from their camera roll using the expo image picker package
//setUploadProgress sets the value I use to pass the progress values to the Progress.Bar component

const submitVideo = (accountID) => {
  const response = await uploadVideo(
    accountID,
    media.uri,
    function (progress) {
      setUploadProgress(progress);
    };
//code to do something with the response from the server
}

POST 请求本身正在工作,因为视频已正确上传到服务器,并且我从服务器获得了预期的响应。只是 onUploadProgress 给我带来了问题。

感谢任何可以提供帮助的人!

标签: reactjsreact-nativeaxios

解决方案


推荐阅读