이현규
이현규

Reputation: 97

Spring @RequestParam on multipart/form-data

Before beginning my question, English is not accurate because I am Korean.

I use Spring Boot 1.5.14.

I am implementing file upload using FormData and 400 error occured.

1. Javascript

    var formData = new FormData();
    formData.append('autoSelect', 'autoSelect');
    formData.append('file', fileObj);

    $.ajax({
        url: '/api/portfolios/' + pofolNo + '/main-image',
        type: 'PUT',
        enctype: 'multipart/form-data',
        processData: false,
        contentType: false,
        data: formData,
        async: false,
    });

2. Spring Controller (not worked)

    @PutMapping("{pofolNo}/main-image")
    public CommonApiResponse changePortfolioMainImage(
        @PathVariable("pofolNo") Integer pofolNo,
        @RequestParam("autoSelect") String autoSelect,
        @RequestParam("mainImage") MultipartFile mainImage) {

        log.debug("check : {} / {} / {}", pofolNo, autoSelect, mainImage);
        return ok(null);
    }

The above code results in a 400 error saying that the autoSelect parameter not present.

So I check HttpServletRequest.getParameter("autoSelect") like this.

3. Spring Controller (worked)

    @PutMapping("{pofolNo}/main-image")
    public CommonApiResponse changePortfolioMainImage(
        @PathVariable("pofolNo") Integer pofolNo,
        HttpServletRequest request,
        @RequestParam("mainImage") MultipartFile mainImage) {

        log.debug("check : {} / {} / {}", pofolNo, request.getParameter("autoSelect"), mainImage);
        return ok(null);
    }

The above code results is successful.

What is the difference? I can't understand @RequestParam is not wokred but worked with HttpServletRequest.

Upvotes: 3

Views: 9466

Answers (1)

Huy Nguyen
Huy Nguyen

Reputation: 2061

The second don't work, because it require not null for @RequestParam("autoSelect") String autoSelect;

Except you must provide the default value or require=false

The third always work because it only inject HttpServletRequest. But please careful, the value might be still null.

It's quite different how to get parameter value in multipart/form-data and depend on your servlet api version.

More clearly explanation about multipart and servlet api version:

How to upload files to server using JSP/Servlet?

Upvotes: 3

Related Questions