春季MVC多个文件上传 [英] spring MVC multiple files upload

查看:49
本文介绍了春季MVC多个文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using spring MVC and JSP. I want to upload 2 files, issue is only one file is getting uploaded. Below is the code:

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

下面是弹簧控制器代码:

Below is the spring controller code:

@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();
                }
            }
        }
    }
}

调试控制器时,即使上传两个文件,fileUpload也仅显示一个文件.

When I debug the controller, fileUpload is showing only one file, even when I upload two files.

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

Below is the code added in Spring-mvc.xml

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

推荐答案

就是这样.您无需在表单中使用超过input标记即可选择多个文件

Just do like this. you dont need to have more than input tag in your form to select multiple files

  <input type="file" name="fileUpload" size="50" multiple/>    

通过单击键盘上的ctrl选项,用户可以在系统中选择多个文件.

It will allow users to select multiple files in their sytem by clicking ctrl option in keyboard.

然后,在您的动作课中,根据需要进行操作.

And then, in your action class, do your stuff as you wanted.

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

Make sure fileUpload variable as file array in your bean class

这篇关于春季MVC多个文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆