ajaxfileupload+spring mvc 单张图片上传

//jsp页面 1、首先引入ajaxfileupload.js 2、form一定要配上enctype="multipart/form-data" 3、给要上传的file定义
  一个id
<%@ page language="java" contentType="text/html;charset=utf-8"  pageEncoding="utf-8"%>
<%@include file="/WEB-INF/views/common/taglib.jsp"%>
<script type="text/javascript" src="${ctx}/static/web/js/ajaxfileupload.js"></script>
<link rel="stylesheet" type="text/css" href="${ctx}/static/common/validform/validate.css"/>
<script type="text/javascript" src="${ctx}/static/common/validform/Validform_v5.3.2.js"></script>
<script>
    $(function(){
        $("#sub").click(function(){
            var datas = $("#subForm").serialize();
            var type =$("#type").val();
            var toExplain=$("#toExplain").val();
            var code = $("#code").val();
            var uploadUrl ="${ctx}/web/mbr/vefify/proveUploadSub?type="+type+"&toExplain="+toExplain+"&code="+code;
                $.ajaxFileUpload({
                    url:uploadUrl,
                    secureuri:false,
                    fileElementId:'pic',
                    dataType: 'json',
                    success: function (data, status){
                    var data = jQuery.parseJSON(data);
                        if(data.errCode == false){
                            $("#err").html("验证码错误");
                        }else if(data.msg == true && data.pic == "true"){
                            alert("上传资料成功");
                            $("#err").html("");
                        }else if(data.msg == false && data.pic == "false"){
                            alert("上传资料失败");
                            alert("图片上传失败");
                        }
                    },error: function (data, status, e){
                        alert("调用方法失败");
                    }
                });
        });
    })
</script>
<!--右边的内容 开始-->
<div class="user_right_main">
    <form:form action="" id="subForm"  enctype="multipart/form-data">
        <div class="user_help alert">
            <font color="#FF0000">*</font> 必须是本人的真实、有效资料
        </div>
        <div class="user_right_border">
            <div class="l">资料上传:</div>
            <div class="c">
                <input type="file" name="pic"  id="pic"/> 上传最大的图片为1M,上传的格式为jpg.gif
            </div>
        </div>
        <div class="user_right_border">
            <div class="l">上传类型:</div>
                <div class="c">
                    <select name="type" autocomplete="off" id="type">
                    <option value="27">居住证(暂住证)</option>
                    <option value="26">住房公积金</option>
                    <option value="25">社保</option>
                    <option value="24">行驶证</option>
                    <option value="23">驾驶证</option>
                    <option value="22">地税证</option>
                    <option value="21">国税证</option>
                    <option value="20">生活照</option>
                    <option value="19">房产证</option>
                    <option value="18">居住地租赁合同</option>
                    <option value="17">水费发票或电费发票或煤气发票(最近2个月)</option>
                    <option value="16">营业执照副本(需要彩色)</option>
                    <option value="15">机构代码证</option>
                    <option value="14">公司银行流水(近三个月)</option>
                    <option value="13">劳动合同或单位证明或工作证</option>
                    <option value="12">近3个月银行代发工资记录或个人转账存款记录</option>
                    <option value="11">学位证书或毕业证书</option>
                    <option value="10">户口本</option>
                    <option value="9">结婚证/单身证明</option>
                    <option value="8">家人身份证正面</option>
                    <option value="7">家人身份证背面</option>
                    <option value="6">固定电话通话记录清单(最近2个月)</option>
                    <option value="5">手机通话记录清单(最近2个月)</option>
                    <option value="4">借款承诺书</option>
                    <option value="3">信用报告 </option>
                    <option value="2">其他借款说明</option>
                    <option value="1">其他能说明您收入、资产、职务或素质的有效资料(凡不属于以上内容的都放在此)</option>
                </select>                                    </div>
                </div>
                <div class="user_right_border">
                    <div class="l">备注说明:</div>
                    <div class="c">
                        <textarea cols="50" rows="5"id="toExplain" name="toExplain" ></textarea>
                    </div>
                </div>
        
                <div class="user_right_border">
                    <div class="l" style="font-weight:bold; float:left;">验证码:</div>
                    <div class="c">
                        <input class="code" id="code"datatype="*"name="code" type="text" maxlength="5" style=" width:118px; *margin-left:3px;" errormsg="验证码格式错误"nullmsg="请输入验证码!" placeholder="请输入验证码" ajaxUrl="${ctx}/web/mbr/verifyCode">&nbsp;
                        <img src="${ctx}/VerifyCode" alt="点击刷新" onclick="this.src='${ctx}/VerifyCode?t='+Math.random();" align="absmiddle" style="cursor:pointer; display:inline-block;zoom:1;*display:inline; *float:none;height:30px;">
                        <span id="err" style="color: red"></span>
                    </div>
                </div>
                <div class="user_right_border">
                    <div class="e"></div>
                    <div class="c">
                        <input type="button" id="sub" class="btn-action" value="确认提交" size="30" />
                    </div>
                </div>
            </form:form>
    
</div>

//后台上传方法如下
/**
     * 上传方法
     * liyiyi
     * @param multipartFile
     * @param request
     * @param reqs
     * @return
     */
    public Map<String,Object> uploadImg(HttpServletRequest request,、
    @RequestParam Map<String, Object> reqs){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> multipartFile = multipartRequest.getFiles("pic");
        String fileName = null;
        String fileType = null;
        FileOutputStream fos =null;
        //图片上传
        for (MultipartFile file : multipartFile) {
            fileName = file.getOriginalFilename();
            fileType= fileName.indexOf(".") != -1 ? fileName.substring(fileName.lastIndexOf("."), fileName.length()) : null;
            fileType = fileType.toLowerCase();
            if(fileType.equals(".jpg") || fileType.equals(".png")){
                if(file.getSize() > 0){
                    try {
                        byte[] bytes = file.getBytes();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }
                    System.out.println("文件的大小为"+file.getSize());
//                  String path = request.getSession().getServletContext().getRealPath("/upload");
                    String rootPath = System.getProperty("catalina.home")+File.separator+"webapps"+File.separator;
                    String path = rootPath+"upload";
                    File file2 = new File(path);
                    if(!file2.exists()){
                        System.out.println("path不存在");  
                        file2.mkdir();
                    }
                    try {
                        fos = new FileOutputStream(path+File.separator+fileName);
                        FileCopyUtils.copy(file.getInputStream(), fos);
//                      String pathSuc ="localhost:8080"+File.separator+"upload"+File.separator+fileName;
                        reqs.put("msg","true");
                        reqs.put("path",fileName);
                        System.out.println("文件上传成功");
                    } catch (Exception e) {
                        reqs.put("msg","false");
                        e.printStackTrace();
                    }
                    
                }
            }
        }
                return reqs;
    }
}
//在springmvc.xml中要配置,也要引入上传的Jar包
<!-- 文件上传解析器-->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
        p:defaultEncoding="UTF-8">
    </bean>


你可能感兴趣的:(ajaxfileupload+spring mvc 单张图片上传)