如何在Flutter的Dio应用中结合Schema上传图片至Django API
实现Flutter上传图片+帖子详情到Django API
你之前用jsonEncode提交JSON数据的方式不支持文件上传,得改用multipart/form-data格式来同时发送表单字段和文件,以下是修改后的完整实现:
修改后的代码
import 'dart:io'; import 'package:dio/dio.dart'; static Future<Account?> add({ required String title, required int price, required String det, required String cate, required int w, required int h, required int bed, required int bath, required int location_id, required File image, // 新增图片参数 }) async { try { // 构建FormData,整合表单字段和图片文件 FormData formData = FormData.fromMap({ "user_id": Account.currentAcc.id, "title": title, "price": price, "details": det, "category": cate, "bedroom": bed, "bathroom": bath, "width": w, "height": h, "location_post_id": location_id, // 图片字段名要和Django后端接收的名称一致 "image": await MultipartFile.fromFile( image.path, filename: image.path.split('/').last, // 保留原文件名 ), }); Response res = await Dio().post( 'http://10.0.2.2:8000/api/post/add-post', data: formData, // 直接传FormData,无需jsonEncode ); // 若需要解析返回数据生成Account实例,可在此处处理 // return Account.fromJson(res.data); return null; } catch (e) { print('上传失败: $e'); return null; } }
核心注意事项
- Django后端要适配
multipart/form-data格式,获取图片的示例代码:# 在Django视图中获取上传的图片 image_file = request.FILES.get('image') # 后续可将图片保存至本地或云存储 - 调用该方法时,需要传入通过图片选择插件(如image_picker)获取的
File类型图片对象。 - 移除了原代码中的
jsonEncode,FormData会自动设置正确的请求头类型。
内容的提问来源于stack exchange,提问作者Mohammed Al Shemmari
相关产品推荐
相关产品推荐

