AjaxFileUploader 实现稳健上传

由于项目需求在上传头像是需要使用异步上传文件,在上传的过程中需要对文件进行校验:规则如下:宽度和高

度大于200,宽高比要小于2,大小小于2M。

    我这里使用的是AjaxFileUploader这个组件,服务器使用Struts处理文件。

    实例:

  1. <form action="" id="imageForm" enctype="multipart/form-data" method="POST">  
  2.     <input type="file" name="userPhoto" id="userPhoto">  
  3.     <input type="button" value="上传" id="shangchuan">  
  4. </form>  

    这里需要引入两个js文件:jQuery、ajaxfileUpload

  1. <script type="text/javascript" src="${basePath }/resource/js/plugin/jquery-1.6.min.js"></script>  
  2.  <script type="text/javascript" src="${basePath }/resource/js/grzx/ajaxfileupload.js"></script>  


   js文件:

[javascript] view plaincopyprint?
  1. //上传头像  
  2.     $("#shangchuan").click(function(){  
  3.         var file = $("#userPhoto").val();  
  4.         if(file==""){  
  5.             alert("请选择上传的头像");  
  6.             return;  
  7.         }  
  8.         else{  
  9.             //判断上传的文件的格式是否正确  
  10.             var fileType = file.substring(file.lastIndexOf(".")+1);  
  11.             if(fileType!="png"&&fileType!="jpg"){  
  12.                 alert("上传文件格式错误");  
  13.                 return;  
  14.             }  
  15.             else{  
  16.                 var url = "/symh/user/uploadPhoto_uploadPhoto.action?nowtime="+new Date().getTime();  
  17.                 $.ajaxFileUpload({  
  18.                     url:url,  
  19.                     secureuri:false,  
  20.                     fileElementId:"userPhoto",        //file的id  
  21.                         dataType:"text",                  //返回数据类型为文本  
  22.                     success:function(data,status){  
  23.                         if(data=="1"){  
  24.                             alert("请上传宽度大于200像素和高度大于200像素的图片");  
  25.                         }  
  26.                         else if(data=="2"){  
  27.                             alert("请上传宽高比不超过2的图片");  
  28.                         }  
  29.                         else if(data=="3"){  
  30.                             alert("请上传文件大小不大于2M的图片");  
  31.                         }     
  32.                         else{  
  33.                             $("#uploadImage").hide();  
  34.                             $("#srcImg").attr("src",data);  
  35.                             $("#previewImg").attr("src",data);  
  36.                             $("#cutImage").show();  
  37.                             $("#bigImage").val(data);  
  38.                             cutImage();         //截取头像  
  39.                         }  
  40.                     }  
  41.                 })  
  42.             }  
  43.         }  
  44.     })  


    后台处理程序:UploadPhotoAction.java

    1. public class UploadPhotoAction {  
    2.     private File userPhoto;  
    3.     private String userPhotoContentType;  
    4.     private String userPhotoFileName;  
    5.   
    6.     public File getUserPhoto() {  
    7.         return userPhoto;  
    8.     }  
    9.   
    10.     public void setUserPhoto(File userPhoto) {  
    11.         this.userPhoto = userPhoto;  
    12.     }  
    13.   
    14.     public String getUserPhotoContentType() {  
    15.         return userPhotoContentType;  
    16.     }  
    17.   
    18.     public void setUserPhotoContentType(String userPhotoContentType) {  
    19.         this.userPhotoContentType = userPhotoContentType;  
    20.     }  
    21.   
    22.     public String getUserPhotoFileName() {  
    23.         return userPhotoFileName;  
    24.     }  
    25.   
    26.     public void setUserPhotoFileName(String userPhotoFileName) {  
    27.         this.userPhotoFileName = userPhotoFileName;  
    28.     }  
    29.   
    30.     /**  
    31.      * 用户上传图像  
    32.      */  
    33.     public void uploadPhoto(){  
    34.         try {  
    35.             HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);  
    36.             response.setCharacterEncoding("UTF-8");  
    37.               
    38.             FileInputStream fis1 = new FileInputStream(getUserPhoto());         //保存文件  
    39.             FileInputStream fis2 = new FileInputStream(getUserPhoto());        //判断文件  
    40.             int i = this.checkImage(fis2);  
    41.             if(i==1){  
    42.                 response.getWriter().print("1");  
    43.             }  
    44.             else if(i==2){  
    45.                 response.getWriter().print("2");  
    46.             }  
    47.             else if(i==3){  
    48.                 response.getWriter().print("3");  
    49.             }  
    50.             else {   //文件正确、上传  
    51.                 //得到文件名  
    52.                 String photoName = getPhotoName(getUserPhotoFileName());  
    53.                   
    54.                 FileOutputStream fos = new FileOutputStream(getSavePath()+"\\"+photoName);  
    55.                 byte[] buffer = new byte[1024];    
    56.                 int len = 0;    
    57.                 while ((len = fis1.read(buffer))>0) {    
    58.                     fos.write(buffer,0,len);       
    59.                 }    
    60.                 //处理文件路径,便于在前台显示  
    61.                 String imagPathString = dealPath(getSavePath()+"\\"+photoName);  
    62.                 response.getWriter().print(imagPathString);  
    63.                   
    64.             }  
    65.         }   
    66.         catch (IOException e) {  
    67.             e.printStackTrace();  
    68.         }  
    69.       
    70.     }  
    71.       
    72.     /**  
    73.      * 重新命名头像名称:用户编号+头像后缀  
    74.      */  
    75.     public String getPhotoName(String photoName){  
    76.         //获取用户  
    77.         HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);  
    78.         UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");  
    79.           
    80.         //获取文件的后缀  
    81.         String[] strings = photoName.split("\\.");  
    82.         String hz = strings[1];  
    83.           
    84.         //构建文件名  
    85.         String fileName = userBean.getUserId()+"."+hz;  
    86.         return fileName;  
    87.     }  
    88.       
    89.     /**  
    90.      * 获取上传路径  
    91.      */  
    92.     public String getSavePath(){  
    93.         return ServletActionContext.getServletContext().getRealPath("upload/photos");  
    94.     }  
    95.       
    96.     /**  
    97.      * 判断上传的头像是否合法  
    98.      * 规则:宽度和高度大于200、宽高比小于2、大小小于2M  
    99.      * 宽度或者高度<200 返回1  
    100.      * 宽高比>2 返回2  
    101.      * 大小大于2M 返回 3  
    102.      * 正确 返回 0  
    103.      */  
    104.     public int checkImage(FileInputStream fis){  
    105.         try {  
    106.             BufferedImage image = ImageIO.read(fis);  
    107.             double width = image.getWidth();  
    108.             double height = image.getHeight();  
    109.             if(width<200||height<200){  
    110.                 return 1;  
    111.             }  
    112.             else if(width/height>2){  
    113.                 return 2;  
    114.             }  
    115.             else if(fis.available()/(1024*1024)>2){  
    116.                 return 3;  
    117.             }  
    118.             else {  
    119.                 return 0;  
    120.             }  
    121.         } catch (IOException e) {  
    122.             e.printStackTrace();  
    123.         }  
    124.         return 1;  
    125.     }  
    126.       
    127.     /**  
    128.      * 处理头像路径  
    129.      */  
    130.     public String dealPath(String path){  
    131.         String[] strings = path.split("\\\\");  
    132.         String string2 = "/";  
    133.         for (int i = strings.length-4; i < strings.length; i++) {  
    134.             if(i==strings.length-1){  
    135.                 string2 = string2+strings[i];  
    136.             }  
    137.             else {  
    138.                 string2 = string2+strings[i]+"/";  
    139.             }  
    140.                   
    141.         }  
    142.         return string2;  
    143.     }  
    144. }  
posted @ 2013-04-17 21:45  季相相  阅读(188)  评论(0编辑  收藏  举报