You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为react-native-fetch-polyfill添加onUploadProgress上传进度事件

解决react-native-fetch-polyfill中onUploadProgress事件的添加问题

嘿,别纠结啦,我来帮你理清这个问题!其实onUploadProgress回调是直接作为fetch请求配置对象的属性存在的,和你已经写好的method、body、headers是同级的,直接加进去就行~

给你修改好的完整代码,你可以直接参考使用:

fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({ title: 'foo', body: 'bar', userId: 1 }),
  headers: { "Content-type": "application/json; charset=UTF-8" },
  // 就在这里添加onUploadProgress回调!
  onUploadProgress: function(progressEvent) {
    // 这里可以处理上传进度的逻辑
    if (progressEvent.lengthComputable) {
      const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
      console.log(`当前上传进度:${percentCompleted}%`);
    } else {
      console.log('无法计算上传进度');
    }
  },
  // 如果需要超时功能,直接在配置里加timeout属性,单位是毫秒
  timeout: 10000 // 比如设置10秒超时
})
.then(function(data) {
  console.log(data);
})
.catch(function(error) {
  console.log('Fetch Error :-S', error);
});

简单补充两点:

  • onUploadProgress会在上传数据的过程中被多次触发,通过progressEvent里的loaded(已上传字节数)和total(总字节数),就能轻松计算出上传进度。
  • 超时功能也不需要额外复杂操作,直接在配置对象里添加timeout属性并设置毫秒数即可。

内容的提问来源于stack exchange,提问作者1110

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:55:08