简体   繁体   中英

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.

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/

Your <form> in your view code is with method as POST

<form action="/upload" enctype="multipart/form-data" method = "post"> 

In controller change @RequestMapping("/upload") to below

@RequestMapping(value = "/upload", method = RequestMethod.POST)

you need something to handle loading the form a @GetMapping .
The @RequestMapping i think defaults to get. So when you are "getting" the page it tries to hit your method that is expecting a file. take a look at my example

I would recommend using @RequestPart. If you are uploading a file using from-data try to rewrite the code like below:

    @PostMapping("/upload")
public ResponseEntity<CustomResponse> uploadFile(@RequestPart(value = "file",required = true) MultipartFile file,
                                 @RequestPart(value = "metadata",required = true) Metadata metadata,
                                 HttpServletResponse response) 

I have had similar issue, in my case the reason was the name of the input tag of the form was not matching with @RequestParam("fileUpload") annotation parameters.

 @PostMapping("/add")
public String addFile(@RequestParam("fileUpload") MultipartFile fileUpload, Model model, Authentication authentication) {

    User loggeduser = userService.getUser(authentication.getName());
    File newFile = new File();

    String fileName = StringUtils.cleanPath(fileUpload.getOriginalFilename());

    File fileaux = filesService.getFileByName(fileName);
    int result = -1;
    if (fileaux != null) {
        model.addAttribute("result", false);
        model.addAttribute("message", "File already exists");
        return "result";
    } else {
        try {
            newFile.setFilename(StringUtils.cleanPath(fileName));
            newFile.setContentType(fileUpload.getContentType());
            newFile.setFileSize(String.valueOf(fileUpload.getSize()));
            newFile.setUserId(loggeduser.getUserid());
            newFile.setFileData(fileUpload.getBytes());
            result = filesService.addFile(newFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    if (result < 0) {
        model.addAttribute("result", false);
    } else {
        model.addAttribute("result", true);
    }

    return "result";
}

it must match with the input form tag in the HTML file.

<form action="#" enctype="multipart/form-data" th:action="@{/file/add}" method="POST">
                        <div class="container">
                            <div class="row" style="margin: 1em;">
                                <div class="col-sm-2">
                                    <label for="fileUpload">Upload a New File:</label>
                                </div>
                                <div class="col-sm-6">
                                    <input type="file" class="form-control-file" id="fileUpload" name="fileUpload">
                                </div>
                                <div class="col-sm-4">
                                    <button type="submit" class="btn btn-dark" id="uploadButton">Upload</button>
                                </div>
                            </div>
                        </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM