Flutter : Multipart File request not working

4,157

Solution 1

when one of your file is null, you should avoid adding it to the request body.

if(imageFile != null){
    request.files
        .add(await http.MultipartFile.fromPath('image', imageFile.path));
}
if(signatureFile != null){
request.files.add(
        await http.MultipartFile.fromPath('signature', signatureFile.path));
}

its because signatureFile.path is going to cause an error here

Solution 2

using dio package should work

   Future<bool> updateImage(var pickedFile) async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();` <br/>
    var token = sharedPreferences.getString("token");
    Dio dio = Dio(); 
    final File file = File(pickedFile.path);
   String fileName = file.path.split('/').last;
   dio.options.headers["authorization"] = token;
   FormData formData = FormData.fromMap({
     "image": await MultipartFile.fromFile(file.path),
     });
    try {
     var response = await dio.post(API.kBASE_URL, data: formData);
           if (response.statusCode == 200) {
           return true;
           } else {
                   return false;
                 }
          } catch (r) {
                        return false;
                       }
     }
Share:
4,157
Abir Ahsan
Author by

Abir Ahsan

Currently, I am working as a Jr. flutter mobile app Developer. Contact to me +8801716422666

Updated on December 26, 2022

Comments

  • Abir Ahsan
    Abir Ahsan 11 months

    I want to upload image by multipart File request. With using this code When I pass two image files then it's working fine. But when I want to pass one image file and another is null then it's not working. where is the problem? How can I solve this ?

    Here is my code -

    Future<Map<String, dynamic>> updateprofile(
          UpdateProfileInfo updateProfileInfo,
          File imageFile,
          File signatureFile) async {
    
        String url = "$baseAPIUrl/update-profile-info";
        String _token = await SavedData().loadToken();
        String authorization = "Bearer $_token";
    
        final headers = {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          "Authorization": authorization
        };
    
        var request = http.MultipartRequest("POST", Uri.parse(url));
    
        request.headers.addAll(headers);
        request.fields.addAll(updateProfileInfo.toJson());
    
        request.files
            .add(await http.MultipartFile.fromPath('image', imageFile.path));
        request.files.add(
            await http.MultipartFile.fromPath('signature', signatureFile.path));
    
        print(" Update Profile Json ${updateProfileInfo.toJson()}");
        print("Request Fields ${request.fields}");
        http.StreamedResponse response = await request.send();
    
        String respStr = await response.stream.bytesToString();
        dynamic respJson;
    
        try {
          respJson = jsonDecode(respStr);
        } on FormatException catch (e) {
          print(e.toString());
        }
    
        print('API ${response.statusCode}\n  $respJson');
    
        bool isSuccess = response.statusCode == 200;
        var data = json.decode(respStr);
    
        return {
          'isSuccess': isSuccess,
          "message": isSuccess ? data["success"]["message"] : null,
          "name": isSuccess ? data["success"]["name"] : null,
          "classgroup": isSuccess ? data["success"]["classgroup"] : null,
          "image": isSuccess ? data["success"]["image"] : null,
          "error": isSuccess ? null : data['error']['message'],
        };
      }
    

    Here is postman Screenshot

    1.

    enter image description here

    2. POSTMAN Generated code for Dart - http

    enter image description here

    • pskink
      pskink almost 3 years
      how do you know that " ... it's not working."?
    • Shubham Narkhede
      Shubham Narkhede almost 3 years
      means you want to pass multiple images for single request in one parameter right ?
    • Abir Ahsan
      Abir Ahsan almost 3 years
      @ShubhamNarkhede Sorry, not one parameter. I passed two parameters File imageFile and File signatureFile
    • Abir Ahsan
      Abir Ahsan almost 3 years
      @pskink By seeing my output, It's seems like that, It's not hit to my API
    • Shubham Narkhede
      Shubham Narkhede almost 3 years
    • Abir Ahsan
      Abir Ahsan almost 3 years
      @ShubhamNarkhede Sorry, I edited my comment. please check
    • Abir Ahsan
      Abir Ahsan almost 3 years
      @pskink don't have any response, waited about 1 minute but no response. But when I passed one parameter, it's response me quickly
    • pskink
      pskink almost 3 years
    • Abir Ahsan
      Abir Ahsan almost 3 years
      @pskink I found the exact issue, When I use this code for two Image File, but send one Image, and another is null then it don't reponse
    • John Joe
      John Joe almost 3 years
      @AbirAhsan so it fixed?
    • Abir Ahsan
      Abir Ahsan almost 3 years
      @JohnJoe exact problem found but not fixed
    • John Joe
      John Joe almost 3 years
      @AbirAhsan have you checked why it is null ? Or try send a null image using postman, did the server return anything?
    • Abir Ahsan
      Abir Ahsan almost 3 years
      @JohnJoe When I send a null image by postman It's send to my api a dummy path that's why it's working. postman code- request.files.add(await http.MultipartFile.fromPath('signature', '/path/to/file'));
  • Lakshmi
    Lakshmi over 2 years
    Not working . Getting an error "Unhandled Exception: FileSystemException: Cannot retrieve length of file, path = 'File: '/data/user/0/com.tcs.tryon_v5/cache/image_picker34320352152‌​83692220.jpg'' (OS Error: No such file or directory, errno = 2)"