Flutter中使用Retrofit实现单/多图上传(Form-Data格式)求助
Flutter Retrofit FormData图片上传问题解决
你的代码核心问题是直接传递File对象给@Part,而Flutter Retrofit要求使用MultipartFile类型处理文件上传,以下是修正后的单张/多张图片上传实现:
1. 确认依赖完整性
确保pubspec.yaml包含必要依赖:
dependencies: retrofit: ^4.0.0 dio: ^5.0.0 path: ^1.8.0
2. 单张图片上传修正
接口定义修改
@POST('$ENDPOINTS') @MultiPart() Future<dynamic> uploadImage( @Header("Authorization") String authorization, @Part(name: 'file') MultipartFile image, @Part(name: 'filetype') String fileType );
调用代码修改
// 将File转换为MultipartFile File file = File(imagePath); MultipartFile multipartFile = await MultipartFile.fromFile( file.path, filename: file.path.split('/').last, // 提取文件名 contentType: MediaType('image', 'jpeg'), // 按实际图片类型设置,png对应'png' ); // 注意:Authorization通常需带Bearer前缀,如"Bearer myToken" response = await apiClient .someClass() .uploadImage("Bearer myToken", multipartFile, "imageType");
3. 多张图片上传实现
接口定义
@POST('$ENDPOINTS') @MultiPart() Future<dynamic> uploadImages( @Header("Authorization") String authorization, @Part(name: 'file') List<MultipartFile> images, @Part(name: 'filetype') String fileType );
调用代码
List<String> imagePaths = [path1, path2, path3]; // 多张图片路径集合 List<MultipartFile> multipartFiles = []; for (String path in imagePaths) { File file = File(path); MultipartFile filePart = await MultipartFile.fromFile( file.path, filename: file.path.split('/').last, contentType: MediaType('image', 'jpeg'), ); multipartFiles.add(filePart); } response = await apiClient .someClass() .uploadImages("Bearer myToken", multipartFiles, "imageType");
额外注意事项
- 若后端要求多文件参数名为
file[],需将@Part(name: 'file')改为@Part(name: 'file[]') - 确保图片的
contentType与实际文件格式匹配,避免后端解析失败
内容的提问来源于stack exchange,提问作者Priyesh Sharma
相关产品推荐
相关产品推荐

