Flutter/Dart中使用Dio库下载PDF文件无响应问题排查
Dio下载PDF无预期效果排查
我用Dio库编写了下载PDF文件的代码,但点击下载按钮后没有出现预期效果。以下是我的代码及控制台输出:
代码
Future download2(Dio dio, String url, String savePath) async { String? token = await this.widget.appController.storage.read(key: "token"); Map<String, String> headers = { "Content-Type": "application/json", "Accept": "application/json", "Authorization": "Bearer " + (token ?? ""), }; try { Response response = await dio.get( url, onReceiveProgress: showDownloadProgress, options: Options( headers: headers, responseType: ResponseType.bytes, followRedirects: false, validateStatus: (status) { return status! < 500; }), ); print(response.headers); File file = File(savePath); var raf = file.openSync(mode: FileMode.write); raf.writeFromSync(response.data); await raf.close(); } catch (e) { print(e); } } void showDownloadProgress(received, total) { if (total != -1) { print((received / total * 100).toStringAsFixed(0) + "%"); } } ElevatedButton( child: Text('Download Bill pdf'), onPressed: () async { var tempDir = await getTemporaryDirectory(); String fullPath = tempDir.path + "/boo2.pdf'"; print('full path ${fullPath}'); download2(dio, pdfUrl, fullPath); } )
控制台输出
I/flutter (24548): full path /data/user/0/com.iccs.electromobilityapp/cache/boo2.pdf' I/flutter (24548): 100% I/flutter (24548): connection: keep-alive I/flutter (24548): last-modified: Mon, 17 Oct 2022 10:17:34 GMT I/flutter (24548): cache-control: no-cache, no-store, max-age=0, must-revalidate I/flutter (24548): date: Fri, 21 Oct 2022 08:58:48 GMT I/flutter (24548): vary: Origin I/flutter (24548): vary: Access-Control-Request-Method I/flutter (24548): vary: Access-Control-Request-Headers I/flutter (24548): content-type: text/html;charset=UTF-8 I/flutter (24548): pragma: no-cache I/flutter (24548): x-xss-protection: 1; mode=block I/flutter (24548): content-language: en I/flutter (24548): server: nginx/1.15.12 I/flutter (24548): accept-ranges: bytes I/flutter (24548): content-length: 6425 I/flutter (24548): x-frame-options: DENY I/flutter (24548): x-content-type-options: nosniff I/flutter (24548): expires: 0
问题分析与修复方案
1. 文件路径错误
控制台显示的路径末尾多了一个单引号:/boo2.pdf',这会导致系统无法正确识别文件路径,直接修改路径代码:
String fullPath = tempDir.path + "/boo2.pdf";
2. 请求头设置错误
当前请求头的Accept是application/json,但我们要下载PDF,应该告诉服务器我们接受PDF格式:
Map<String, String> headers = { "Accept": "application/pdf", // 修改为PDF格式 "Authorization": "Bearer " + (token ?? ""), }; // 移除Content-Type,GET请求不需要发送JSON请求体,该字段多余
3. 异步调用未等待
download2是异步函数,onPressed里没有用await,可能导致异常无法被捕获,修改为:
onPressed: () async { var tempDir = await getTemporaryDirectory(); String fullPath = tempDir.path + "/boo2.pdf"; print('full path ${fullPath}'); await download2(dio, pdfUrl, fullPath); // 添加await等待下载完成 }
4. 接口返回非PDF内容
控制台里的content-type是text/html,说明接口返回的是HTML页面(可能是权限错误、资源不存在等),需要:
- 确认
pdfUrl是否正确指向PDF资源 - 检查token是否有效,是否具备访问该PDF的权限
- 直接在浏览器或Postman中用相同token访问
pdfUrl,验证返回内容是否为PDF
可选:验证下载结果
在download2的try块末尾添加文件验证逻辑,方便排查问题:
// 下载完成后检查文件状态 if (await file.exists()) { print("文件已保存至:${file.path}"); // 若要直接打开PDF,可引入open_file库调用:await OpenFile.open(file.path); } else { print("文件保存失败"); }
内容的提问来源于stack exchange,提问作者Bill Tertis
相关产品推荐
相关产品推荐

