0

I am struggling with Multipart file upload in Spring controller. I've read multiple questions, googles, but nothing seems to work.

I get

error: "Bad Request"
exception: "org.springframework.web.multipart.support.MissingServletRequestPartException"
message: "Required request part 'file' is not present"

My BE controller:

@RequestMapping(value = "/zip", method = RequestMethod.POST)
public void readFile(@RequestParam("file") MultipartFile file) throws IOException { 
// code
}

FE, angularJS:

service.getZip = function getZip(file) {
    var formData = new FormData();
    formData.append('file', file);
    return $http({
        method: 'POST',
        url: CONSTANTS.readFile,
        data: formData,
        headers: {'Content-Type': undefined}
    }) .then(function (response) {
        var data = response.data;
        return data.id;
    });
}

HTML:

<input type="file" id="file" name="file" accept=".txt"/>

also application.properties contain:

spring.http.multipart.enabled=false

UPDATE:

I no longer get that error when following @Byeon0gam advice to remove @RequestParam from my controller, but the my file is null as it comes to controller. Although in FE service, as I see, it's not empty:

enter image description here

cinnamon
  • 79
  • 3
  • 10
  • Are you sure you are not mixing upload and download logic? You have a Post mapping on a method called `readFile`. You are also using `url: CONSTANTS.readFile`. Do you want to upload a file from client to server or download a file from server to client? –  Oct 03 '18 at 18:27
  • I want both - upload a file from a client, and immediately return response, which consists of files, generated from uploaded file. – cinnamon Oct 03 '18 at 18:36
  • I don't know angularJS, so I have no ide what kind of request is generated from that code. BUT: you can create a standard HTML form with SUBMIT button. Spring controllers work smoothly with HTML file-upload. So if it works, then start the developer console and check the exact lookout of the request what is sent when you hit the submit button. Then play with the JS code until it creates the exact same request. – Selindek Oct 03 '18 at 20:29
  • add this enctype="multipart/form-data" to your form. – tharanga-dinesh Oct 04 '18 at 08:24

1 Answers1

0

change the Content-Type in your FE to:

headers: {'Content-Type': 'x-www-form-urlencoded'}

hope it will work for you.