0

I want to update the user with a name and/or image.

The name is always on the input because I fetched from the database but the fileUpload is optional.

How do I make my controller handle an optional parameter for the fileUpload?

Atm, if I don't upload something I'm getting

HTTP Status 400 - Required request part 'fileUpload' is not present

Spring controller

@RequestMapping(value = "/user/update", method = RequestMethod.POST)
public @ResponseBody String updateUser(HttpSession session,@RequestParam("name") String name, @RequestParam("fileUpload") MultipartFile image) {
    String loggedUser = session.getAttribute("loggedUser").toString();
    return User.updateUser(loggedUser,name,image);
}

Ajax

function updateUserSettings() {
var name = $('#userName').val();
var formData = new FormData();
formData.append("name", name);
formData.append("fileUpload", file);
$.ajax({
    type: 'post',
    url: '/user/update',
    data: formData,
    enctype: 'multipart/form-data',
    processData: false,
    contentType: false
});

}

1

1 Answer 1

4

Change this:

... @RequestParam("fileUpload") MultipartFile image

to:

... @RequestParam(value="fileUpload", required=false) MultipartFile image

Refer to the docs for more info on the available switches.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.