Felipe Mosso
Felipe Mosso

Reputation: 3927

How to submit a form with no file uploaded spring mvc

I have a form which has some input text fields and one input file field for registering some entries in my database.

Now I'm creating another form to edit the same entry. I retrieve the data from the database and fill in this another form, which has the same fields of the first one. I do not fill in, though, the input file value since, for security reasons, I cannot do it programatically.

So I let the user to edit whatever he wants and update that entry. However, if the user does not change the file input field, my code is submitting the form with an empty file input and thus I'm having a 400 (Bad request) error since my ajax request does not find my servlet.

Here is some coding:

In my Controller class:

@RequestMapping(value = RestUriConstants.SUBMETER, method = RequestMethod.POST)
public @ResponseBody JsonResponse submeter(@RequestPart("exercicio") final Exercicio exercicio,
            @RequestPart("file") final MultipartFile file) {
            ...
}

And the Ajax request:

    var exercicioObject = new Object();
    exercicioObject.id = id;
    exercicioObject.nome = nome;
    exercicioObject.grupo = grupo;

    var formData = new FormData();
    formData.append("file", file.files[0]);
    formData.append('exercicio', new Blob([JSON.stringify(exercicioObject)], {
           type : "application/json"
    }));

            $.ajax({
                url : '/Project/exercicio/submeter',
                type : 'POST',
                dataType : 'text',
                data : formData,
                 processData : false,
                contentType : false
            });

As you can see I'm setting a Json object which will be passed to the server as Exercicio object, and the file will be passed as MultipartFile object.

As I'm not setting any MultipartFile object, I think Spring is not finding my URL, which needs two parameters (Exercicio and MultipartFile) but I have no idea how I can pass anything on MultipartFile just to make Spring redirect my request to the correct method in the server.

Upvotes: 0

Views: 957

Answers (1)

minion
minion

Reputation: 4353

Please try using @RequestPart(required=false) to ignore it when you don't pass.

Upvotes: 1

Related Questions