spring MVC 多文件上传

use*_*675 4 jsp spring-mvc

我正在使用 spring MVC 和 JSP。我想上传 2 个文件,问题是只有一个文件正在上传。下面是代码:

<form id="myform" name="myform" action="/createRequest.htm" enctype="multipart/form-data" method="POST">
//form elements like textbox, checkbox
    <tr>
        <th class="RelReqstAllign"></th><td> (Or)<input type="file" name="fileUpload" size="50"/></td>
    </tr>
    <tr>
        <th class="RelReqstAllign"></th><td><input type="file" name="fileUpload" size="50" /></td>
    </tr>
</form>
Run Code Online (Sandbox Code Playgroud)

下面是弹簧控制器代码:

@RequestMapping(value = "/createRequest", method = RequestMethod.POST)
public ModelAndView createRequest(final HttpServletRequest request,
        final HttpServletResponse response,
        final @ModelAttribute("spRequestDTO") SPRequestDTO dto,
        final BindingResult beException,
        final @RequestParam("buttonName") String buttonName,
        @RequestParam CommonsMultipartFile[] fileUpload) throws IOException {
    if (fileUpload != null && fileUpload.length > 0) {
        for (CommonsMultipartFile aFile : fileUpload) {

            System.out.println("Saving file: "
                    + aFile.getOriginalFilename());

            if (!aFile.getOriginalFilename().equals("")) {
                try {
                    aFile.transferTo(new File(saveDirectory + aFile.getOriginalFilename()));
                } catch (IllegalStateException e) {

                    e.printStackTrace();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当我调试控制器fileUpload时,即使我上传了两个文件,也只显示一个文件。

下面是在 Spring-mvc.xml 中添加的代码

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
Run Code Online (Sandbox Code Playgroud)

use*_*273 5

就这样做吧。您不需要input在表单中添加多个标签来选择多个文件

  <input type="file" name="fileUpload" size="50" multiple/>    
Run Code Online (Sandbox Code Playgroud)

它将允许用户通过单击ctrl键盘中的选项来选择系统中的多个文件。

然后,在你的行动课上,做你想做的事。

确保fileUpload变量作为 bean 类中的文件数组

  • 您可以使用`@RequestParam("fileUpload[]") MultipartFile fileUpload[]` (2认同)