Flutter应用提交图片至API时触发PathNotFoundException错误求助
问题解决:PathNotFoundException 及 API 二进制图片上传修正
1. 核心错误:路径被额外引号包裹
你在生成imagePaths时,给每个路径添加了双引号:
final List<String> imagePaths = images.map((file) => '"${file.path}"').toList();
这会让实际路径变成带引号的格式(例如"/storage/emulated/0/xxx.jpg"),File类无法识别这种带引号的路径,直接抛出PathNotFoundException。
修正代码:
移除路径的引号包裹,直接传递原始文件路径:
final List<String> imagePaths = images.map((file) => file.path).toList();
2. API 二进制图片上传修正
你提到API需要以二进制形式接收图片,但当前代码是将图片转成Base64后放入JSON中发送,不符合二进制上传的要求。应使用multipart/form-data格式提交文件,以下是修正后的API请求代码:
import 'dart:convert'; import 'dart:io'; import 'package:http/http.dart' as http; Future<Map<String, dynamic>> fetchAlerteApi( String typeAlertes, List<String> imagePaths, String geoPointer, ) async { try { var request = http.MultipartRequest( 'POST', Uri.parse('http://enika.afriklabtech.com/api/alertes/create'), ); // 添加文本字段 request.fields['type_alerte'] = typeAlertes; request.fields['geo_pointer'] = geoPointer; // 添加二进制图片文件 for (String imagePath in imagePaths) { File imageFile = File(imagePath); if (await imageFile.exists()) { var multipartFile = await http.MultipartFile.fromPath( 'images', // 需与后端API接收图片的字段名保持一致 imagePath, filename: imagePath.split('/').last, ); request.files.add(multipartFile); } else { throw Exception('图片文件不存在:$imagePath'); } } // 发送请求 var response = await request.send(); var responseBody = await response.stream.bytesToString(); // 处理重定向 if (response.statusCode == 301 || response.statusCode == 302) { String? redirectUrl = response.headers['location']; if (redirectUrl != null) { var redirectRequest = http.MultipartRequest( 'POST', Uri.parse(redirectUrl), ); redirectRequest.fields.addAll(request.fields); redirectRequest.files.addAll(request.files); var redirectResponse = await redirectRequest.send(); var redirectResponseBody = await redirectResponse.stream.bytesToString(); return jsonDecode(redirectResponseBody); } else { throw Exception('重定向目标URL为空'); } } else if (response.statusCode == 201) { return jsonDecode(responseBody); } else { throw Exception('请求失败,状态码:${response.statusCode}'); } } catch (e) { print('请求错误:$e'); rethrow; } }
3. 额外优化建议
- 在处理图片前,先检查文件是否存在,避免因文件被删除等情况触发异常:
for (var file in images) { if (!await file.exists()) { print('图片文件不存在:${file.path}'); // 可在此处提示用户或跳过该文件 continue; } } - 确保
selectedItem和images的状态管理逻辑正确,避免出现空值或无效数据。
内容的提问来源于stack exchange,提问作者Ouattara Souleymane
相关产品推荐
相关产品推荐

