Search code examples
javahtmlspring-bootfile-upload

Spring Boot Required request part 'file' is not present


I am trying to create a file upload utility and am getting the following error when I click on the submit button. It starts uploading and then suddenly has this error:

There was an unexpected error (type=Bad Request, status=400).
Required request part 'file' is not present

I don't have a stacktrace, that's all that's displayed in my window or my console. I've looked for other solutions and they all ended up being someone forgot to include name="file" in their html file. I have made sure it's included and am still getting the error.

Below is my upload form:

<div id="custom-search-input">
<label>Select a file to upload</label>
    <form action="/upload" enctype="multipart/form-data" method = "post"> 
        <div class="input-group col-md-12">
            <input type="file" name="file" class="search-query form-control"/>
            <span class="input-group-btn">
                <button type="submit" class="btn btn-success">Upload </button>
            </span>
        </div>
    </form>
</div>

This is my controller method for uploading:

@Value("${upload.path}")
    private String path;

    @RequestMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model, HttpSession session) throws IOException {
            if(!file.isEmpty()) {
                //Get the user
                User user = (User) session.getAttribute("user");
                //Get the file name
                String fileName = file.getOriginalFilename();
                InputStream is = file.getInputStream();
                //Store the uploaded file into the users directory in the system path
                Files.copy(is, Paths.get(path + user.getNetworkId() + "\\"  + fileName),StandardCopyOption.REPLACE_EXISTING);

            return "redirect:/success.html";

        } else {

            return "redirect:/index.html";
        }   
    }

Also would like to note I tried this for my upload method:

public String upload(@RequestParam(name="file",required=true) MultipartFile file, Model model, HttpSession session) 

For reference, this is what I was referrencing.

As per some of the answers below, I tried creating a PostMapping method stand alone, as well as @RequestMapping(value="/upload", method = RequestMethod.POST) I am still getting the error.


Solution

  • After a while, I was able to solve this issue: In my application.properties file I added the following:

    spring.servlet.multipart.max-file-size=128MB
    spring.servlet.multipart.max-request-size=128MB
    spring.http.multipart.enabled=true
    upload.path=/export/home/