Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JPA – Successful Storage of Post Only When Input Tag Name is "file"

I’m implementing a feature to store posts using JPA. In the service class, I have the following method:

public void boardWrite(Board board, MultipartFile file) throws Exception, IOException {
    if (!file.isEmpty()) {
        String path = "E:\\image\\sell";
        UUID uuid = UUID.randomUUID();
        String filename = uuid + "_" + file.getOriginalFilename();
        File saveFile = new File(path, filename);
        file.transferTo(saveFile);
        board.setPhoto(filename);
        board.setPhoto_url("/sell/" + filename);
    }

    boardRepository.save(board);
}

Additionally, in the controller, I call it as follows:

@PostMapping("/add")
public String add(Board board, MultipartFile file) throws Exception {
    service.boardWrite(board, file);
    return "redirect:list";
}

The part of the HTML where I get the file input is as follows:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<tr>
    <td width="150" align="center">Photo Attachment</td>
    <td>
        <input type="file" name="file" class="form-control" id="inputGroupFile02">
    </td>
</tr>

When I set the name attribute of the input tag to "file", the post is successfully stored. However, if I use a different name such as "file1" or "photo", it results in a 400 error. I’m curious about the reason behind this behavior. Why does it only work when the input tag name is "file"?

>Solution :

The argument MultipartFile file is equivalent to: @RequestParam MultipartFile file

If you don’t specify a name with the @RequestParam annotation the variable name is used as default. In your case this is file.

You can use other names by either changing your variable name or adding the @RequestParam annotation with a name:
@RequestParam("photo") MultipartFile file.

If you have to support multiple names, create proxy methods:

@PostMapping(value="/add", params = "photo")
public String addPhoto(@RequestParam(value="photo", required=true) MultipartFile file){
   return addFile(file);
}

@PostMapping(value="/add", params = "file")
public String addFile(@RequestParam(value="file", required=true) MultipartFile file){
   // ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading