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

如何用JavaScript和PHP实现显示上传行数的加载器

Excel导入进度实时显示问题描述

我试过各种方法,始终没法实现需求:用户上传Excel文件后,把文件里的数据行导入数据库。目前JavaScript和PHP脚本都能正常运行,但想在导入过程中给用户显示“当前第current_line行/共total_lines行”的加载进度。

我的实现方案是:PHP端通过finances/import接口用for循环导入数据,同时迭代更新session变量;再通过finances/import_progress接口读取进度。但加载器只会在导入完成后才更新,我把checkImportProgress里的fetch改成XHR并尝试用onprogress方法,还是没解决问题。

相关JavaScript代码如下:

fetch(baseurl + 'finances/import', {
    method: 'POST',
    ContentType: 'multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD',
    body: form
  })
  .then(response => response.json())
  .then(json => {
    if (json.success) {
      //获取上传Excel文件的总行数
      nbrlignes = json.nbrlines
      document.querySelector('.infoslignes').style.display = 'block'
      document.querySelector('.ligneimport').innerHTML = 0
      document.querySelector('.lignetotal').innerHTML = nbrlignes
      fetch(baseurl + 'finances/import_excel', {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          page: document.querySelector('input[name="page"]').value,
          file: json.file
        })
      })
      setInterval(checkImportProgress, 500, nbrlignes)
    } else {
      document.querySelector('.error-import').style.display = 'block'
      document.querySelector('.error-import').innerHTML = json.message
      document.querySelector('.import-text').style.display = 'block'
      document.querySelector('.import-progress').style.display = 'none'
    }
  })

function checkImportProgress(nbrlignes) {
  fetch(baseurl + 'finances/import_progress/' + nbrlignes)
    .then(response => response.json())
    .then(json => {
      document.querySelector('.import-progress-bar').style.width = ((json.row / nbrlignes) * 100) + '%'
      document.querySelector('.import-progress-bar').innerHTML = Math.round(((json.row / nbrlignes) * 100)) + '%'
      document.querySelector('.ligneimport').innerHTML = json.row
      if (nbrlignes === json.row)
        clearInterval()
    })
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 04:27:20