简体   繁体   English

Spring Boot Required 请求部分“文件”不存在

[英]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.我正在尝试创建文件上传实用程序,但在单击submit按钮时出现以下错误。 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.我没有堆栈跟踪,这就是我的 window 或我的控制台中显示的所有内容。 I've looked for other solutions and they all ended up being someone forgot to include name="file" in their html file.我一直在寻找其他解决方案,但最终都是有人忘记在他们的 html 文件中包含name="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:这是我的controller上传方法:

@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.根据下面的一些答案,我尝试单独创建一个PostMapping方法,以及@RequestMapping(value="/upload", method = RequestMethod.POST)我仍然收到错误。

After a while, I was able to solve this issue: In my application.properties file I added the following:过了一会儿,我能够解决这个问题:在我的 application.properties 文件中,我添加了以下内容:

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>使用方法为POST

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

In controller change @RequestMapping("/upload") to below在控制器@RequestMapping("/upload")更改为下面

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

you need something to handle loading the form a @GetMapping .你需要一些东西来处理加载表单@GetMapping
The @RequestMapping i think defaults to get. @RequestMapping我认为默认为获取。 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.我建议使用@RequestPart。 If you are uploading a file using from-data try to rewrite the code like below:如果您使用 from-data 上传文件,请尝试重写如下代码:

    @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.我有类似的问题,在我的例子中,原因是表单的输入标签的名称与@RequestParam("fileUpload")注释参数不匹配。

 @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.它必须与 HTML 文件中的输入表单标签匹配。

<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>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring Thymeleaf所需的请求部分“文件”不存在 - Spring Thymeleaf Required request part 'file' is not present Spring 文件上传 - “所需的请求部分不存在” - Spring File Upload - 'Required request part is not present' 如何修复 Spring 引导分段上传中的“所需请求部分不存在” - How to fix "Required request part is not present" in a Spring Boot multipart upload React 和 Spring 引导不存在所需的请求部分“图像” - Required request part 'image' is not present with React and Spring Boot React Spring 使用多部分表单数据启动应用程序 - 所需的请求部分“文件”不存在 - React Spring Boot App Using Multipart Form Data - Required request part 'file' is not present MissingServletRequestPartException:所需的请求部分“文件”不存在 Springboot - MissingServletRequestPartException: Required request part 'file' is not present Springboot Tomcat:所需的请求部分“文件”不存在 - Tomcat : Required request part 'file' is not present 出现“不存在所需的请求部分&#39;文件&#39;”错误 - Getting “Required request part 'file' is not present” error AngularJS JSON Spring MVC 应用程序中的文件上传 400 Bad Request Required 请求部分不存在 - File Upload in AngularJS JSON Spring MVC application 400 Bad Request Required request part is not present 所需的请求部分“文件”不存在。 尝试上传图像,角度-&gt;春天 - Required request part 'file' is not present. Trying upload an image, angular -> spring
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM