图片预览异步上传及Sping处理

首先需要插件配置ajaxfileupload.js下面可下载
jsp代码:
<img id="showImg1" alt="" src="" onclick="file1()">
<input type="file" id="file" name="file" style="display:none;" onchange="upload()"  />
js代码:
function file1(){
document.getElementById("file").click();
}
function upload(){
$.ajaxFileUpload({ 
        url : '${basePath}/qfOrder/uploadImg.action', //用于文件上传的服务器端请求地址 
        secureuri : false, //一般设置为false 
        fileElementId : 'file', //文件上传空间的id属性  <input type="file" id="file" name="file" /> 
        type : 'post', 
        dataType : 'json', //返回值类型 一般设置为json 
        success : function(data, status) //服务器成功响应处理函数 
        { 
             var imgUrl = data.imgUrl;
             $('#img1').val(imgUrl);
             $('#showImg1').attr('src','${basePath}'+'/'+imgUrl);
        }, 
        error : function(data, status, e)//服务器响应失败处理函数 
        { 
            alert(data.msg); 
        } 
    });
}
后台Java sping代码:
@RequestMapping(value = "uploadImg")
public void uploadImg(HttpServletRequest request,HttpServletResponse response,
@RequestParam(value="file",required=false) MultipartFile[] file) throws Exception{
//获得物理路径webapp所在路径 
String pathRoot = request.getSession().getServletContext().getRealPath("/"); 
        String path=""; 
        List<String> listImagePath=new ArrayList<String>();
        JSONObject json = new JSONObject();
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        try {
        if(file!=null&&file.length>0){
             for (MultipartFile mf : file) { 
                     if(!mf.isEmpty()){ 
                         //生成uuid作为文件名称 
                         String uuid = UUID.randomUUID().toString().replaceAll("-",""); 
                         //获得文件类型(可以判断如果不是图片,禁止上传) 
                         String contentType=mf.getContentType(); 
                         //获得文件后缀名称 
                         String imageName=contentType.substring(contentType.indexOf("/")+1);
                         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                         path="DDQF/images/"+sdf.format(new Date())+"/" +uuid+"."+imageName;
                         File imgFile = new File(pathRoot+path);
                         if(!imgFile.exists()){
                         imgFile.mkdirs();
                         }
                         mf.transferTo(imgFile); 
                         listImagePath.add(path); 
                     } 
                 }
             jsonMap.put("msg", "图片上传成功");
             jsonMap.put("imgUrl", listImagePath.get(0));
             }
} catch (Exception e) {
jsonMap.put("msg", "图片上传失败");
}
json.putAll(jsonMap);
response.getWriter().append(json.toString());
}

猜你喜欢

转载自guoyulong005.iteye.com/blog/2376522