所需的多部分文件参数“文件”在弹簧 mvc 中不存在

2022-09-03 00:23:28

我正在尝试将图片上传到我的春季mvc应用程序的功能。

jsp 部分:

...
<form method="POST"  action="uploadImage" enctype="multipart/form-data">
                <div class="load-line">
                    <input type="file" class="file"/>
                    <input type="submit" value="Upload">
...

配置:

... 
<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
...

控制器:

 @RequestMapping(value="/member/createCompany/uploadImage", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(
            @RequestParam("file") MultipartFile file){
        String name = "image_name";
        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name + "-uploaded")));
                stream.write(bytes);
                stream.close();
                return "You successfully uploaded " + name + " into " + name + "-uploaded !";
            } catch (Exception e) {
                return "You failed to upload " + name + " => " + e.getMessage();
            }
        } else {
            return "You failed to upload " + name + " because the file was empty.";
        }
    }

选择图片后,我单击上传并看到错误消息:

HTTP Status 400 - Required MultipartFile parameter 'file' is not present

我错了什么?


答案 1

您尚未指定属性 ,@RequestParam(“textFile”) 需要 name ,name

 <input type="file" class="file" name="textFile"/>

答案 2

将名称属性添加到“文件”输入标记

<input type="file" class="file" name="file"/>

推荐