SpringMVC下实现多文件上传功能

关于SpringMVC上传文件的效率问题,网上有人做过比较
http://blog.csdn.net/a1314517love/article/details/24183273
实际结果表明通过SpringMVC rosolver方式的效率远胜字节流方式的上传,下面贴上上传多文件的代码:
1.连接../upload/uploadFiles 上传文件

@Controller
@RequestMapping(value = "upload/")
public class UploadFileCtr {

    @RequestMapping(value = "uploadFiles", method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public String uploadFiles(@RequestParam("file") CommonsMultipartFile files[], HttpServletRequest request,
            HttpServletResponse response) {
        System.out.println("uploadFiles-multipartResolver:" + files.length);
        // 判断file数组不能为空并且长度大于0
        String allPaths = "";
        if (files != null && files.length > 0) {
            // 循环获取file数组中得文件
            try {
                for (int i = 0; i < files.length; i++) {
                    MultipartFile file = files[i];
                    // 保存文件
                    if (!file.isEmpty()) {
                        String savePath = "D:\\" + "upload";
                        String filename = file.getOriginalFilename();
                        filename = filename.substring(filename.lastIndexOf("\\") + 1);
                        // 得到上传文件的扩展名
                        String fileExtName = filename.substring(filename.lastIndexOf("."));
                        filename = System.currentTimeMillis() + fileExtName;
                        String filePath = savePath + File.separator + filename;
                        System.out.println("uploadFiles-filePath:" + filePath);
                        // 转存文件
                        file.transferTo(new File(filePath));
                        allPaths+=(filename+";");
                    }
                }
                return allPaths;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}

2.Html代码
由于上方的后台代码@RequestParam(“file”),故html中所有需要上传文件的input需要设置name为”file”,否则会匹配不到

 <form  method="post" enctype="multipart/form-data">  
       <input type="file" name="file">  
       <input type="submit" value="提交">  
    </form>  

3.如果在上传文件同时,需要上传参数:

@RequestMapping(value = "uploadUserRole", method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
    @ResponseBody
    public ModelAndView uploadUserRole(@RequestParam("file") CommonsMultipartFile files[],@RequestParam String user_id, HttpServletRequest request,
            HttpServletResponse response,HttpSession session) {
        if (files != null && files.length > 0) {
            try {
                excelUtil = new ExcelUtil();
                for (int i = 0; i < files.length; i++) {
                    MultipartFile file = files[i];
                    // 保存文件
                    if (!file.isEmpty()) {
                        String savePath = request.getServletContext().getRealPath("./")+"upload";
                        File uploadDir = new File(savePath);
                        if (!uploadDir.exists()) {
                            uploadDir.mkdir();
                        }
                        String filename = file.getOriginalFilename();
                        File finalFile = new File(savePath + File.separator + filename);
                        if(finalFile.exists()){
                            finalFile.delete();
                        }
                        // 转存文件
                        file.transferTo(finalFile);
                        //此处可使用user_id
                    }
                }
                insertStatus = "insert ok";
            } catch (Exception e) { 
                insertStatus = e.toString();
                e.printStackTrace();
            }
        }
        session.setAttribute("status", "ok");
        ModelAndView  model = new ModelAndView("fail");   
        //model.addObject("userName", userName);  
        return model;
    }

html代码:

<form  method="post" enctype="multipart/form-data">  
       <input type="file" name="file">  
       <input type="text" name="user_id">  
       <input type="submit" value="提交">  
    </form>  

4.(3)中上传成功后会跳转到fail.jsp,需要在Spring-mvc添加bean配置

 <!-- 对模型视图添加前后缀 -->
     <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/view/" p:suffix=".jsp"/>

然后在view下新建fail.jsp,即可

5.上传解析器配置,在spring-mvc中添加:

<!-- 配置文件上传类型解析器 multipartResolver -->
    <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件最大尺寸,单位为5MB -->
        <property name="maxUploadSize" value="5000000" />
        <property name="defaultEncoding" value="UTF-8" />
        <property name="uploadTempDir" value="upload/temp" />
    </bean>
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值