如何在请求中发送文件

时间:2020-05-16 01:55:43

标签: android ios flutter

嗨,我在这里堆放了我使用了2个程序包http和dio,经过2天的尝试代码,我找不到一个工作 所以我将其与packag dio一起使用,我想发送带有请求的文件

问题出在这里“” dio.post(“”他们在软件包中找不到帖子

import 'package:dio/dio.dart' as dio;

dio.FormData formData=new dio.FormData.fromMap({
  "file": await dio.MultipartFile.fromFile(imagePath,filename: imageName),
  "description": "fghfghfghfgh",
  "type": "Profile",
  "selected": "YES",
  "category_id": "3",
});
dio.Response response= await dio.post("https://top-food.coders-ries/images/create", body: formData);

2 个答案:

答案 0 :(得分:0)

您可以尝试一下吗?:

    import 'package:dio/dio.dart'

    postData() async{
        Response response;
        Dio dio = Dio();
        FormData formData=new FormData.fromMap({
        "file": await MultipartFile.fromFile(imagePath,filename: imageName),
        "description": "fghfghfghfgh",
        "type": "Profile",
        "selected": "YES",
        "category_id": "3",});
        response= await dio.post("https://top-food.coders-ries/images/create", data: formData);
}

答案 1 :(得分:0)

问题出在文件扩展中,所以我用mime liberary设置了它,代码在下面

   Dio dio =new Dio();
      final formData = FormData.fromMap({
        "description": "descriptoin",
        "type": "Profile",
        "selected": "YES",
        "food_id": idOfFood,
      });
      //build the file
      final mimeTypeData = mime.lookupMimeType(filePath, headerBytes: [0xFF, 0xD8]).split('/');
      final file = await MultipartFile.fromFile(filePath, filename: 'image', contentType: MediaType(mimeTypeData[0], mimeTypeData[1]));
      MapEntry<String, MultipartFile> mapEntry =MapEntry(file.filename, file);
      //add the file to request
      formData.files.add(mapEntry);
      Response requestImage = await dio.post("https://top-food.coders-artists.com/api/foods/images/create", data: formData,);`enter code here`