使用SpringMVC实现文件上传功能

最近做项目多次用到文件上传功能,并且项目底层框架使用的是springMVC,虽不难但容易忘记,在这里记录下(实现多文件动态上传(暂时完成,有缺陷):直接copy项目代码,仅供参考)

view页面代码如下:

<form:form id="inputForm" modelAttribute="userEnterprise" action="${ctx}/sys/userEnterprise/save" method="post" class="form-horizontal" enctype="multipart/form-data">
    <tr>
        <td>        
            <input name="docName"  maxlength="255" class="required"/>
        </td>
        <td>                    
            <input name="infoFile" type="file" class="leg" />
        </td>
        <td>
            <input name="remarks" maxlength="255" class="required "/>
        </td>

    </tr>
</form:form>

注意form标签必须含有enctype=”multipart/form-data”元素

controller代码如下:

@RequestMapping(value = "save")
    public String save(@RequestParam(value="infoFile",required=false)MultipartFile[] files , UserEnterprise userEnterprise, HttpServletRequest request , HttpServletResponse response , Model model, RedirectAttributes redirectAttributes) {
        if (!beanValidator(model, userEnterprise)){
            return form(userEnterprise, model);
        }
        for (MultipartFile f : files) {
            boolean isSuccess = FileUtils.saveFileToFolder(f, FileUtils.readPropertiesFile("zhongdai.properties", "zhongdai_enterprise_user_document_disc")+"/"+userEnterprise.getUser().getId());
            if(!isSuccess){
                logger.debug("保存企业用户资料失败!");
                addMessage(redirectAttributes, "保存企业用户资料失败!");
                return "redirect:"+Global.getAdminPath()+"/sys/userEnterprise/?repage";
            }
        }

        for (int i = 0; i < files.length; i++) {
            String docName = request.getParameter("docName"+i);
            String remarks = request.getParameter("remarks"+i);
            String subPath = FileUtils.readPropertiesFile("zhongdai.properties", "zhongdai_enterprise_user_document_db");   //获取保存地址目录
            String path=subPath+"/"+userEnterprise.getUser().getId()+"/"+files[i].getOriginalFilename();    //拼接全路径
            documentService.save(new UserEnterpriseDocument(userEnterprise,docName,path,new Date(),remarks));
        }
        userEnterpriseService.save(userEnterprise);
        addMessage(redirectAttributes, "保存企业用户信息成功");
        return "redirect:"+Global.getAdminPath()+"/sys/userEnterprise/?repage";
    }

文件上传工具类如下:

public static boolean saveFileToFolder(MultipartFile mFile , String folder , String... rename){
        boolean isSuccess=false;
        if(mFile.isEmpty()){
            log.debug("文件为空");
            return false;
        }

        try {
            //验证磁盘地址是否存在
            File folderPath = new File(folder);
            if(!folderPath.exists()){
                isSuccess= folderPath.mkdir();  //建一个文件夹
            }

            //保存文件
            mFile.transferTo(new File(folder,mFile.getOriginalFilename()));

            //获取文件保存路径
            File file=new File(folderPath.toString(),mFile.getOriginalFilename());

            //是否修改文件名
            if(rename.length <= 0){
                isSuccess=true;
            }else{
                isSuccess = file.renameTo(new File(folderPath,rename[0]));
            }

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

其他方式1():
单个文件上传也可以使用Ajax新版本支持FormData对象,FormData对象是html5的一个对象,目前的一些主流的浏览器都已经兼容

支持以下浏览器版本
1. Chrome 7+
2. Firefox 4.0 (2.0)
3. Internet Explorer 10+
4. Opera 12+
5. Safari 5+
这里不举例了,网上有简单易学使用教程

其他方式:使用jquery.form.js(转载):



<form id="tf">
     <input type="file" name="img"/>
     <input type="text" name="username"/>
     <input type="button" value="提" onclick="test();"/>
</form>

下面使用jquery.form.js的表单插件来提交表单

$("#tf").ajaxSubmit();

额,就是这么简单,你也不要问我为什么就是这么简单,然后它就是会把整个表单,作为一个ajax来提交,同样的,它也支持文件上传!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值