ajaxFileupload异步上传图片

  背景:我们平时在做项目的时候,肯定会遇到上传头像、图片、文件等异步上传的功能,今天就以ajaxFileupload组件上传头像为例总结一下该组件的用法。

      

      Tips:  我在以前的博客中分享过三种上传组件,其实主要代码已经在这篇文章体现了,今天再次总结一下ajaxfileupload这个组件,发现在高版本(1.9以上)的Jquery下ajaxfileupload提示异常,然后我就把ajaxfileupload的jQuery对象都替换成了$就可使用了,对于ajaxFileUpload 报这错jQuery.handleError is not a function,请猛戳   这里,对就是这里。附件是修改好可使用的ajaxfileupload.js文件。

    

     需求:自定义样式【上传】按钮,点击之后【上传】按钮,打开文件选择对话框,选择文件后自动上传,并可预览该图片。

 

     分析:

     1.【上传】按钮是a链接,但是上传文件必然需要一个input type="file"的元素,在点击a链接这个【上传】按钮的时候,触发input type="file"元素的click方法打开文件选择对话框,选择文件后,触发input type="file" 的onchange方法,然后调用ajaxfileupload的上传方法开始上传。

 

     2.服务器端,接收此文件数据,保存到文件服务器上,返回此文件的相对路径,放入一个隐藏域,最后提交表单时,将此相对路径提交给后台保存入库。
     3.预览,通过获取图片的流数据显示图片。

       用到的技术:jquery,ajaxfileupload,springMVC

 

    代码:

    1.HTML片段

    

Html代码   收藏代码
  1. <div class="uploadPicture">  
  2.        <img id="imgHead" src="" width="106" height="122" alt="头像">   
  3.        <input type="file" onchange="uploadHead();" id="basicInfoHead" style="display:none;"  
  4.         name="basicInfoHead" />  
  5.       <input type="hidden" id="basicHeadUrl" >  
  6.        <a href="#basicInfo" id="uploadBasicInfoHead" >上传头像</a>  
  7.       </div>  

  2.JS代码

   

Js代码   收藏代码
  1. //上传头像,触发click方法  
  2.     $('#uploadBasicInfoHead').on('click',function(){  
  3.      $('#basicInfoHead').click();  
  4.     });  
  5.   
  6. function uploadHead(){  
  7.   $.ajaxFileUpload({  
  8.       url:"${pageContext.request.contextPath}/profile/uploadBasicHead",//需要链接到服务器地址   
  9.       secureuri:false,  
  10.       fileElementId:"basicInfoHead",//文件选择框的id属性  
  11.       dataType: 'json',   //json  
  12.       success: function (data) {  
  13.          $("#imgHead").attr("src","${pageContext.request.contextPath}/profile/readImage?imagePath="+data.imagePath);  
  14.         $('#basicHeadUrl').val(data.imagePath);  
  15.       },error:function(XMLHttpRequest, textStatus, errorThrown){  
  16.      alert('上传失败!');  
  17.    }  
  18.   });  
  19. };  

  3.JAVA代码

   

Java代码   收藏代码
  1. //上传文件方法  
  2. @RequestMapping(value = "profile/uploadBasicHead", produces = "text/plain;charset=UTF-8")  
  3.  @ResponseBody  
  4.  public String ajaxUpload(HttpServletRequest request) throws IllegalStateException,  
  5.    IOException {  
  6.   MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
  7.   String fileName = "";  
  8.   String uploadPath = "uploadFile/head/";  
  9.   String path =request.getSession().getServletContext().getRealPath("/")+uploadPath;    
  10.   /*File uploadPathFile = new File(path); 
  11.   if (!uploadPathFile.exists()) {   
  12.    uploadPathFile.mkdir();   
  13.      }*/  
  14.   String realPath = "";  
  15.   for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {  
  16.    String key = (String) it.next();  
  17.    MultipartFile mulfile = multipartRequest.getFile(key);  
  18.    fileName = mulfile.getOriginalFilename();  
  19.    fileName = handlerFileName(fileName);  
  20.    File file = new File(path + retFileName);  
  21.    mulfile.transferTo(file);  
  22.   }  
  23.    realPath = "{\"imagePath\":\""+uploadPath+fileName+"\"}";  
  24.   return realPath;  
  25.  }  
  26.   
  27. //文件名称处理  
  28. private String handlerFileName(String fileName) {  
  29.   //处理名称start  
  30.   fileName = (new Date()).getTime()+"_"+fileName;  
  31. //时间戳+文件名,防止覆盖重名文件  
  32.   String pre = StringUtils.substringBeforeLast(fileName, ".");  
  33.   String end = StringUtils.substringAfterLast(fileName, ".");  
  34.   fileName = Digests.encodeByMd5(pre)+"."+end;//用MD5编码文件名,解析附件名称  
  35.   //处理名称end  
  36.   return fileName;  
  37.  }  
  38.   
  39. //预览,获取图片流  
  40. @RequestMapping(value = "profile/readImage", produces = "text/plain;charset=UTF-8")  
  41.     public void readImage(HttpServletRequest request, HttpServletResponse response){  
  42.      String imagePath = request.getSession().getServletContext().getRealPath("/")+request.getParameter("imagePath");  
  43.      try{  
  44.       File file = new File(imagePath);  
  45.          if (file.exists()) {  
  46.            DataOutputStream temps = new DataOutputStream(response  
  47.              .getOutputStream());  
  48.            DataInputStream in = new DataInputStream(  
  49.              new FileInputStream(imagePath));  
  50.            byte[] b = new byte[2048];  
  51.            while ((in.read(b)) != -1) {  
  52.      temps.write(b);  
  53.      temps.flush();  
  54.            }  
  55.            in.close();  
  56.            temps.close();  
  57.          }   
  58.        } catch (Exception e) {  
  59.         e.printStackTrace();  
  60.        }  
  61.     }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值