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

阅读更多
首先需要插件配置ajaxfileupload.js下面可下载
jsp代码:


js代码:
function file1(){
document.getElementById("file").click();
}
function upload(){
$.ajaxFileUpload({ 
        url : '${basePath}/qfOrder/uploadImg.action', //用于文件上传的服务器端请求地址 
        secureuri : false, //一般设置为false 
        fileElementId : 'file', //文件上传空间的id属性   
        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 listImagePath=new ArrayList();
        JSONObject json = new JSONObject();
        Map jsonMap = new HashMap();
        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());
}
  • ajaxfileupload.zip (2.4 KB)
  • 下载次数: 0
  • jquery-1.11.3.zip (83 KB)
  • 下载次数: 0
  • reservation.zip (2 KB)
  • 下载次数: 0

你可能感兴趣的:(java,jsp)