SpringMVC 上传文件

第一次写博客,希望能通过写博客分享一些自己的心得,同时通过这个过程总结自己用过的一些知识。如果有写得不好的地方,希望能与大家共同学习。

目录

[TOC]来生成目录:


1、springmvc配置MultipartResolver

使用springmvc的上传文件功能必须先在spring配置文件(我这里是spring-beans.xml)中配置MultipartResolver,文件大小可以根据需求自己调整

<!-- SpringMVC上传文件时,需配置MultipartResolver处理器 -->  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 指定所上传文件的总大小不能超过800KB......注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
        <property name="maxUploadSize" value="800000"/>  
    </bean> 
... prompt'''

2、前端js代码

//上传文件用的的ajaxfileupload.js
<script src="js/ajaxfileupload.js"></script>

//文件格式,最好有name,否则可能会报错
<ul class="p10 comment line">
    <li><textarea id="contentId" class="textarea" placeholder="评论内容"></textarea>    </li>
<li>
    <a href="javascript:void(0);" class="img" id="add"><img class="img" src="images/add.jpg" /></a>
</li>
</ul>
<form id="form1" style="width: 1px; height:1px">
    <input type="file" id="upfile" name="myfiles" class="input" accept="image/*" style="opacity: 0;width: 50px">
</form>

//jquery定义选择文件事件
$("#upfile").change(function(){
    if(this.value != ''&&this.value != null&&this.value != undefined) {
    var html='<div class="alert_bg" id="loading"><div class="alert"><div class="bar"><img alt="" src="images/loading.gif"> 正在上传...</div></div></div>';
    $("body").append(html);
    ajaxFileUpload();
    }
});

//文件上传时的处理
function ajaxFileUpload(){  
        $.ajaxFileUpload({  
            type:'GET',
            url:'activity/fileUpload.do?openId='+openid,  
            secureuri:false,                           //是否启用安全提交,默认为false   
            fileElementId:'upfile',               //文件选择框的id属性  
            dataType:'text',                           //服务器返回的格式,可以是json或xml等  
            timeout : 60000,
            error : function(data,textStatus){
            },
            success:function(data){
                data=data.substring(data.indexOf("upload"));
                showImg(data,"");
            }  
        });  
        $("#upfile").remove();
        var input = '<input type="file" id="upfile" name="myfiles" onchange="ajaxFileUpload()" class="input" accept="image/*" style="opacity: 0;width: 50px">';
        $("#form1").append(input);
    }  

//上传成功后的一些处理
function showImg(imgUrl,imgUrlThumb){
    var addObj = parent.$('.comment li #add');
    var newObj = '<a href="javascript:void(0);"><img thumb="'+imgUrlThumb+'" src="'+imgUrl+'" class="img" /></a>'
    $(newObj).insertBefore(addObj);
    $("#loading").remove();
}
... prompt'''

1、后端java代码

/**
* 用户评论里面上传图片
* @param openId
* @param myfiles
* @param request
* @param response
* @return
* @throws IOException
*/
@RequestMapping(value="/fileUpload")  
public String fileUpload(@RequestParam String openId, @RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws IOException{  
    String realPath = request.getSession().getServletContext().getRealPath(UploadFileUtils.PATH);  
    //设置out.print返回的数据的格式
    response.setContentType("text/html; charset=UTF-8");  
    PrintWriter out = response.getWriter();  
    String newFileName = null;  
    for(MultipartFile myfile : myfiles){  
        if(myfile.isEmpty()){  
             out.print("请选择文件后上传");  
             out.flush();  
             return null;
        }else{  
             String originalFilename = myfile.getOriginalFilename();  
             try {  
                 newFileName = UploadFileUtils.uploadFile(myfile,originalFilename,openId,realPath);
             } catch (IOException e) {  
                 out.print("文件上传失败,请重试!!");  
                 out.flush();  
                 return null; 
             }  
        }  
   }  
        out.print(newFileName);  
        out.flush();  
        return null;
} 

/**
 * 上传文件用的工具类
 * @author Administrator
 *
 */
public class UploadFileUtils {
    public static final String PATH = "/upload";
    /**
     * 
     * @param myfile
     * @param path
     * @param prefixName:名称前缀,用于保证名称的唯一性
     * @param prefixPath:文件路径,用于指定上传文件所存放的路径
     * @return
     * @throws IOException
     */
    public static String uploadFile(MultipartFile myfile, String path,String prefixName,String prefixPath) throws IOException{
        String newPath = getfullPath(path, prefixName,prefixPath);
        File newFile = new File(newPath);
        FileUtils.copyInputStreamToFile(myfile.getInputStream(), newFile);

        return newPath;
    } 

    /**
     * 删除文件
     * @param path
     * @return
     */
    public static boolean removeFile(String path){
        if(org.springframework.util.StringUtils.isEmpty(path)) return false;

        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        return true;
    }

    /**
     * 获取文件要上传到服务器的全名
     * @return
     */
    private static String getfullPath(String path, String prefixName, String prefixPath){
        String dateStr = DateUtils.formatDate3(new Date());
        String[] split = dateStr.split("-");
        String discPath = path.substring(path.lastIndexOf("."));
        discPath = prefixName+System.currentTimeMillis()+discPath;
        for (int i = split.length-1;i>=0;i--) {
            discPath = split[i]+"/"+discPath;
        }
        discPath = prefixPath + "/" + discPath;

        return discPath;
    }
}
... prompt'''

4、代码所需jar包

SpringMVC 上传文件总共引入了三个文件:
1、ajaxfileupload.js
2、commons-fileupload-1.2.1.jar
3、commons-io-2.2.jar

总结

springmvc上传文件用到的所有的技术点都已在里面,唯一需要自己不的就是前端的html和js部分。支持多图片和多文件上传。引入的所需文件,我会在稍后上传上来
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值