Flutter image upload to SpringBoot server not working

1,121

Figured it out. Instead of using the new http.MultipartFile() constructor I used this static method:

request.files.add(await http.MultipartFile.fromPath('file', image.path,
    contentType: new MediaType('image', imageType)));
Share:
1,121
starman1979
Author by

starman1979

Full stack developer with 15 years of experience. Mostly worked with Java, Spring and also working with Angular in recent years.

Updated on December 12, 2022

Comments

  • starman1979
    starman1979 over 1 year

    I'm trying to upload an image from my Flutter application using the following code:

    Future<String> saveImage(File image) async {
    
      var stream = new http.ByteStream(DelegatingStream.typed(image.openRead()));
      var length = await image.length();
      String token = "blah"; //token for authentication
    
      var uri = Uri.parse(url);  //I get the URL from some config
    
      Map<String, String> headers = { "Authorization": "Bearer $token", "content-type": "multipart/form-data" };
    
      var request = new http.MultipartRequest("POST", uri);
      request.headers.addAll(headers);
      var multipartFile = new http.MultipartFile('file', stream, length);
    
      request.files.add(multipartFile);
    
      var response = await request.send();
      print(response.statusCode);
      response.stream.transform(utf8.decoder).listen((value) {
        print(value);
      });
    }
    

    But this request fails on my spring-boot server with the following error:

    {"timestamp":1562637369179,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"Required request part 'file' is not present","path":"/api/v1/user/photo"}

    This is what my Java controller method looks like:

    @RequestMapping(value = "/photo", method = RequestMethod.POST, consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<String> uploadImage(@RequestPart(required = true) @RequestParam("file") MultipartFile image) throws IOException {
            }
    

    I would like to mention that the method works if I use postman to upload an image. There seems to be something wrong with my flutter code.

    Thanks for any help.

    • Avi
      Avi almost 5 years
      In @RequestPart default value for required is true so you don't have to mention that and remove @RequestParam instead do this `@RequestPart("file")