文件上传建议基于 dio,支持 Multipart 与进度回调。
0. 依赖
dependencies:
dio: ^5.4.0
1. 上传封装
class UploadClient {
final Dio dio;
UploadClient(this.dio);
Future<void> upload(String path, File file, {required void Function(double) onProgress}) async {
final form = FormData.fromMap({
'file': await MultipartFile.fromFile(file.path),
});
await dio.post(
path,
data: form,
onSendProgress: (sent, total) {
if (total > 0) onProgress(sent / total);
},
);
}
}
2. 使用方式
final client = UploadClient(Dio());
await client.upload('/upload', file, onProgress: (p) {
Log.d('upload', 'progress=${(p * 100).toInt()}%');
});
3. 常见坑点
- 权限未处理:读取本地文件失败
- 大文件超时:需调整超时时间
- 断点续传:需服务端支持
4. 实践清单
- Multipart 上传
- 进度回调
- 错误处理