Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MissingServletRequestParameterException

Tags:

spring

angular

I'm passing a formData object to my Spring back-end:

imageBanner(banner: File, bannerPath: string, id: number, callback: (response) => void){
    var formData = new FormData();
    formData.append('name', banner.name);
    console.log(formData.get('name'));
    formData.append('file', banner);
    console.log(formData.get('file'));

    this.sendPost("/upload/" + bannerPath, formData, response => {
        callback(response);
    });

}

The console log shows:

1.jpg 
File {name: "1.jpg", lastModified: 1496737372408, lastModifiedDate: Tue Jun 06 2017 10:22:52 GMT+0200 (W. Europe Daylight Time), webkitRelativePath: "", size: 38983…}

So it looks like the formData has some values.

In the back-end I have this:

@RequestMapping(value="/rest/upload/localeventbanner", method=RequestMethod.POST, headers = "content-type!=multipart/form-data")
    public @ResponseBody String uploadFileHandler(@RequestParam("name") String name, @RequestParam("file") MultipartFile file) {

    if (!file.isEmpty()) {
        try {
            log("success");

            return "You successfully uploaded file=" + name;
        } catch (Exception e) {
            log("fail");
            return "You failed to upload";
        }
    } else {
        log("nope");
        return "You failed to upload " + name
                + " because the file was empty.";
    }
}

The return I'm getting in the console is:

"{"timestamp":1502745177167,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required String parameter 'name' is not present","path":"/beheerback/rest/upload/localeventbanner"}"

It says name isn't present but when I log it in the front-end it shows name is present in the formData object.

like image 362
Peter Boomsma Avatar asked Mar 08 '23 08:03

Peter Boomsma


1 Answers

Try to give required = false for name and file, something like:

@RequestParam(value = "name", required = false, defaultValue = "defaultName") String name, @RequestParam(value = "file" , required = false, defaultValue = "defaultFile") MultipartFile file

Then check the values that you're really getting. Also, check the form sent using the network inspector in the dev mode of your browser.

like image 74
juanlumn Avatar answered Mar 21 '23 05:03

juanlumn