简体   繁体   中英

I would like to upload a image and profile data in Multipart/Formdata format in flutter when hit a api i got response failed

Here is my post api code i try to upload file (image from image picker)and profilePojo(data like username ,fname, lastname etc.) when i run code i got result failed . '''

 void addData(final profilePojo) async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
   String token = preferences.getString('token');
FormData formData = FormData.fromMap({
     "file": await MultipartFile.fromFile("./text.txt",filename: "upload.txt"),
   
     "profilePojo":profilePojo,//profilePojo means i pass heaar string of data on button click
});


    String url =pass here url
    http
        .post(
      url,
      headers: {
         HttpHeaders.authorizationHeader: 'Bearer $token',
        // "Content-Type":"multipart/form-data",
        "accept": "application/json",
      },
      body: formData.toString()
      
    )
        .then((response) {
      if (response.statusCode == 200) {
       var myData = json.decode(response.body);
       
       if(myData['result']=="success"){
        setState(() {
          print(myData);//print response  success
          _showDialog();
          getData();
        });}
        else{
        print(response.statusCode);
        
        print(myData);
        }
      } else {
        print(response.statusCode);
        print("object");
      }
    });
  }

'''

I'm currently using dio for this kind of requests, here is my example:

final futureUploadList = imageList.map((img) async {
    print(img.path);
    return MultipartFile.fromFile(img.path);
  });

final uploadList = await Future.wait(futureUploadList);

FormData data = FormData.fromMap({
  "images": uploadList
});
dio.post('/images',
    data: data, options: Options(headers: {'Authorization': 'Bearer abcd'}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM