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

WebView应用使用DownloadManager下载文件失败(进度0%)求助

问题排查与修复建议

一、先确认URL传递的正确性

  • 在Android端的startDownload方法开头添加日志,检查传入的url是否为完整的后端接口地址(例如http://your-server-ip:port/download/xxx.pdf),而非仅文件名:
    Log.d("DownloadDebug", "Received download URL: " + url);
    
  • 查看后端控制台的Attempting to access file at:日志,确认拼接后的文件路径是否有效——如果路径仅为D:\\或包含无效字符,说明前端传递的URL参数存在问题。

二、修复后端接口的路径解析问题

当前后端使用路径参数/:filePath传递文件路径,若文件名包含特殊字符或/,URI编码后易引发解析错误。建议改用查询参数传递:

app.get('/download', (req, res) => {
    // 从查询参数中获取文件路径
    const decodedPath = decodeURIComponent(req.query.filePath);
    const fullPath = path.join('D:\\', decodedPath);

    console.log('Attempting to access file at:', fullPath);

    res.download(fullPath, (downloadErr) => {
        if (downloadErr) {
            if (downloadErr.code === 'ENOENT') {
                !res.headersSent && res.status(404).json({ error: 'File not found' });
            } else {
                !res.headersSent && res.status(500).json({ error: 'Error during file download' });
            }
            console.error('Download error:', downloadErr);
        } else {
            console.log('File downloaded successfully.');
        }
    });
});

前端传递的URL需调整为http://your-server-ip:port/download?filePath=xxx.pdf,避免路径参数的编码冲突。

三、Android端DownloadManager的权限与配置检查

  • 确保AndroidManifest.xml中添加了必要权限:
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Android 10及以下需要存储权限 -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="28" />
    
  • 用浏览器直接访问后端下载URL,验证接口是否能正常返回文件——若浏览器也无法下载,说明后端接口本身存在问题,与Android端无关。
  • 如果前端获取的mimetype为空或错误,可传入application/octet-stream作为兜底值,避免DownloadManager因无法识别文件类型而终止下载。

四、后端接口的错误处理优化

移除多余的fs.access检查,直接通过res.download捕获错误,减少竞态条件(比如文件在fs.access检查后被删除的情况):

app.get('/download/:filePath', (req, res) => {
    const decodedPath = decodeURIComponent(req.params.filePath);
    const fullPath = path.join('D:\\', decodedPath);

    console.log('Attempting to access file at:', fullPath);

    res.download(fullPath, (downloadErr) => {
        if (downloadErr) {
            if (!res.headersSent) {
                res.status(downloadErr.code === 'ENOENT' ? 404 : 500)
                   .json({ error: downloadErr.code === 'ENOENT' ? 'File not found' : 'Download failed' });
            }
            console.error('Download error:', downloadErr);
        } else {
            console.log('File downloaded successfully.');
        }
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 18:07:37