Spring Boot 需要Sping Boot 的请求部分“file”不存在

bhmjp9jg  于 2023-03-02  发布在  Spring
关注(0)|答案(6)|浏览(191)

我正在尝试创建一个文件上传实用程序,当我点击submit按钮时,出现以下错误。它开始上传,然后突然出现此错误:

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

我没有stacktrace,这就是我窗口或控制台中显示的全部内容。我曾寻找过其他解决方案,但最终都是有人忘记在html文件中包含name="file"。我已经确保包含了name="file",但仍然收到错误。
下面是我的上传表格:

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

这是我的上传控制器方法:

@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";
        }   
    }

还想指出的是,我尝试了我的上传方法:

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

作为参考,this是我所参考的。
根据下面的一些答案,我尝试单独创建PostMapping方法,以及@RequestMapping(value="/upload", method = RequestMethod.POST)方法,但仍然出现错误。

mfuanj7w

mfuanj7w1#

过了一会儿,我终于解决了这个问题:在我的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/
dgjrabp2

dgjrabp22#

视图代码中的<form>具有POST方法

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

在控制器中,将@RequestMapping("/upload")更改为以下值

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

unftdfkk3#

您需要一些东西来处理表单a @GetMapping的加载。
我认为默认的@RequestMapping是get,所以当你“get”页面的时候,它会尝试访问你的方法,这个方法需要一个文件。take a look at my example

fdbelqdn

fdbelqdn4#

我建议使用@RequestPart。如果你使用from-data上传文件,尝试重写如下代码:

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

92dk7w1h5#

我遇到过类似的问题,在我的例子中,原因是表单的输入标记的名称与@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";
}

它必须与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>
r7s23pms

r7s23pms6#

在我的例子中,这是一个权限问题,我必须将以下设置切换为ON:

相关问题