javascript代码实例教程-jquery之ajaxfileupload异步上传插件

发布时间:2019-05-06 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了javascript代码实例教程-jquery之ajaxfileupload异步上传插件脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
小宝典致力于为广大程序猿(媛)提供高品质的代码服务,请大家多多光顾小站,小宝典在此谢过。

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

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

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

    实例:

[htML]
<form action="" id="imageForm" enctyPE=";multipart/form-data" method="POST"> 
    <input type="file" name="userPhoto" id="userPhoto"> 
    <input type="button" value="上传" id="shangchuan"> 
</form> 

<form action="" id="imageForm" enctype="multipart/form-data" method="POST">
    <input type="file" name="userPhoto" id="userPhoto">
    <input type="button" value="上传" id="shangchuan">
</form>    这里需要引入两个js文件:jQuery、ajaxfileUpload

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

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

[javascript]
//上传头像  
    $("#shangchuan").click(function(){ 
        VAR file = $("#userPhoto").val(); 
        if(file==""){ 
            alert("请选择上传的头像"); 
            return; 
        } 
        else{ 
            //判断上传的文件的格式是否正确  
            var fileType = file.substring(file.lastIndexOf(".")+1); 
            if(fileType!="png"&&fileType!="jpg"){ 
                alert("上传文件格式错误"); 
                return; 
            } 
            else{ 
                var url = "/symh/user/uploadPhoto_uploadPhoto.action?nowtime="+new Date().getTime(); 
                $.ajaxFileUpload({ 
                    url:url, 
                    secureuri:false, 
                    fileElementId:"userPhoto",        //file的id  
                        dataType:"text",                  //返回数据类型为文本  
                    success:function(data,status){ 
                        if(data=="1"){ 
                            alert("请上传宽度大于200像素和高度大于200像素的图片"); 
                        } 
                        else if(data=="2"){ 
                            alert("请上传宽高比不超过2的图片"); 
                        } 
                        else if(data=="3"){ 
                            alert("请上传文件大小不大于2M的图片"); 
                        }    
                        else{ 
                            $("#uploadImage").hide(); 
                            $("#srcimg").attr("src",data); 
                            $("#previewImg").attr("src",data); 
                            $("#cutImage").show(); 
                            $("#BigImage").val(data); 
                            cutImage();         //截取头像  
                        } 
                    } 
                }) 
            } 
        } 
    }) 

//上传头像
 $("#shangchuan").click(function(){
  var file = $("#userPhoto").val();
  if(file==""){
   alert("请选择上传的头像");
   return;
  }
  else{
   //判断上传的文件的格式是否正确
     var fileType = file.substring(file.lastIndexOf(".")+1);
     if(fileType!="png"&&fileType!="jpg"){
      alert("上传文件格式错误");
      return;
     }
   else{
    var url = "/symh/user/uploadPhoto_uploadPhoto.action?nowtime="+new Date().getTime();
      $.ajaxFileUpload({
       url:url,
       secureuri:false,
       fileElementId:"userPhoto",        //file的id
          dataType:"text",                  //返回数据类型为文本
       success:function(data,status){
        if(data=="1"){
          alert("请上传宽度大于200像素和高度大于200像素的图片");
        }
        else if(data=="2"){
          alert("请上传宽高比不超过2的图片");
        }
        else if(data=="3"){
          alert("请上传文件大小不大于2M的图片");
        } 
        else{
          $("#uploadImage").hide();
          $("#srcImg").attr("src",data);
          $("#PReviewImg").attr("src",data);
          $("#cutImage").show();
          $("#bigImage").val(data);
          cutImage();         //截取头像
         }
       }
    })
   }
  }
 })
    后台处理程序:UploadPhotoAction.java

[html]
public class UploadPhotoAction { 
    private File userPhoto; 
    private String userPhotoContentType; 
    private String userPhotoFileName; 
 
    public File getUserPhoto() { 
        return userPhoto; 
    } 
 
    public void setUserPhoto(File userPhoto) { 
        this.userPhoto = userPhoto; 
    } 
 
    public String getUserPhotoContentType() { 
        return userPhotoContentType; 
    } 
 
    public void setUserPhotoContentType(String userPhotoContentType) { 
        this.userPhotoContentType = userPhotoContentType; 
    } 
 
    public String getUserPhotoFileName() { 
        return userPhotoFileName; 
    } 
 
    public void setUserPhotoFileName(String userPhotoFileName) { 
        this.userPhotoFileName = userPhotoFileName; 
    } 
 
    /** 
     * 用户上传图像 
     */ 
    public void uploadPhoto(){ 
        try { 
            HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE); 
            response.setCharacterEncoding("UTF-8"); 
             
            FileinputStream fis1 = new FileInputStream(getUserPhoto());         //保存文件 
            FileInputStream fis2 = new FileInputStream(getUserPhoto());        //判断文件 
            int i = this.checkImage(fis2); 
            if(i==1){ 
                response.getWrITer().print("1"); 
            } 
            else if(i==2){ 
                response.getWriter().print("2"); 
            } 
            else if(i==3){ 
                response.getWriter().print("3"); 
            } 
            else {   //文件正确、上传 
                //得到文件名 
                String photoName = getPhotoName(getUserPhotoFileName()); 
                 
                FileOutputStream fos = new FileOutputStream(getSavePath()+"//"+photoName); 
                byte[] buffer = new byte[1024];   
                int len = 0;   
                while ((len = fis1.read(buffer))>0) {   
                    fos.write(buffer,0,len);      
                }   
                //处理文件路径,便于在前台显示 
                String imagPathString = dealPath(getSavePath()+"//"+photoName); 
                response.getWriter().print(imagPathString); 
                 
            } 
        }  
        catch (IOException e) { 
            e.printStackTrace(); 
        } 
     
    } 
     
    /** 
     * 重新命名头像名称:用户编号+头像后缀 
     */ 
    public String getPhotoName(String photoName){ 
        //获取用户 
        HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST); 
        UserBean userBean = (UserBean) request.getSession().getAttribute("userBean"); 
         
        //获取文件的后缀 
        String[] strings = photoName.split("//."); 
        String hz = strings[1]; 
         
        //构建文件名 
        String fileName = userBean.getUserId()+"."+hz; 
        return fileName; 
    } 
     
    /** 
     * 获取上传路径 
     */ 
    public String getSavePath(){ 
        return ServletActionContext.getServletContext().getRealPath("upload/photos"); 
    } 
     
    /** 
     * 判断上传的头像是否合法 
     * 规则:宽度和高度大于200、宽高比小于2、大小小于2M 
     * 宽度或者高度<200 返回1 
     * 宽高比>2 返回2 
     * 大小大于2M 返回 3 
     * 正确 返回 0 
     */ 
    public int checkImage(FileInputStream fis){ 
        try { 
            BufferedImage image = ImageIO.read(fis); 
            double width = image.getWidth(); 
            double height = image.getHeight(); 
            if(width<200||height<200){ 
                return 1; 
            } 
            else if(width/height>2){ 
                return 2; 
            } 
            else if(fis.available()/(1024*1024)>2){ 
                return 3; 
            } 
            else { 
                return 0; 
            } 
        } catch (IOException e) { 
            e.printStackTrace(); 
        } 
        return 1; 
    } 
     
    /** 
     * 处理头像路径 
     */ 
    public String dealPath(String path){ 
        String[] strings = path.split("////"); 
        String string2 = "/"; 
        for (int i = strings.length-4; i < strings.length; i++) { 
            if(i==strings.length-1){ 
                string2 = string2+strings[i]; 
            } 
            else { 
                string2 = string2+strings[i]+"/"; 
            } 
                 
        } 
        return string2; 
    } 

public class UploadPhotoAction {
 private File userPhoto;
 private String userPhotoContentType;
 private String userPhotoFileName;

 public File getUserPhoto() {
  return userPhoto;
 }

 public void setUserPhoto(File userPhoto) {
  this.userPhoto = userPhoto;
 }

 public String getUserPhotoContentType() {
  return userPhotoContentType;
 }

 public void setUserPhotoContentType(String userPhotoContentType) {
  this.userPhotoContentType = userPhotoContentType;
 }

 public String getUserPhotoFileName() {
  return userPhotoFileName;
 }

 public void setUserPhotoFileName(String userPhotoFileName) {
  this.userPhotoFileName = userPhotoFileName;
 }

 /**
  * 用户上传图像
  */
 public void uploadPhoto(){
  try {
   HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(ServletActionContext.HTTP_RESPONSE);
   response.setCharacterEncoding("UTF-8");
   
   FileInputStream fis1 = new FileInputStream(getUserPhoto());         //保存文件
   FileInputStream fis2 = new FileInputStream(getUserPhoto());        //判断文件
   int i = this.checkImage(fis2);
   if(i==1){
    response.getWriter().print("1");
   }
   else if(i==2){
    response.getWriter().print("2");
   }
   else if(i==3){
    response.getWriter().print("3");
   }
   else {   //文件正确、上传
    //得到文件名
    String photoName = getPhotoName(getUserPhotoFileName());
    
    FileOutputStream fos = new FileOutputStream(getSavePath()+"//"+photoName);
    byte[] buffer = new byte[1024]; 
    int len = 0; 
    while ((len = fis1.read(buffer))>0) { 
        fos.write(buffer,0,len);    
    } 
    //处理文件路径,便于在前台显示
    String imagPathString = dealPath(getSavePath()+"//"+photoName);
    response.getWriter().print(imagPathString);
    
   }
  }
  catch (IOException e) {
   e.printStackTrace();
  }
 
 }
 
 /**
  * 重新命名头像名称:用户编号+头像后缀
  */
 public String getPhotoName(String photoName){
  //获取用户
  HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
  UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");
  
  //获取文件的后缀
  String[] strings = photoName.split("//.");
  String hz = strings[1];
  
  //构建文件名
  String fileName = userBean.getUserId()+"."+hz;
  return fileName;
 }
 
 /**
  * 获取上传路径
  */
 public String getSavePath(){
  return ServletActionContext.getServletContext().getRealPath("upload/photos");
 }
 
 /**
  * 判断上传的头像是否合法
  * 规则:宽度和高度大于200、宽高比小于2、大小小于2M
  * 宽度或者高度<200 返回1
  * 宽高比>2 返回2
  * 大小大于2M 返回 3
  * 正确 返回 0
  */
 public int checkImage(FileInputStream fis){
  try {
   BufferedImage image = ImageIO.read(fis);
   double width = image.getWidth();
   double height = image.getHeight();
   if(width<200||height<200){
    return 1;
   }
   else if(width/height>2){
    return 2;
   }
   else if(fis.available()/(1024*1024)>2){
    return 3;
   }
   else {
    return 0;
   }
  } catch (IOException e) {
   e.printStackTrace();
  }
  return 1;
 }
 
 /**
  * 处理头像路径
  */
 public String dealPath(String path){
  String[] strings = path.split("////");
  String string2 = "/";
  for (int i = strings.length-4; i < strings.length; i++) {
   if(i==strings.length-1){
    string2 = string2+strings[i];
   }
   else {
    string2 = string2+strings[i]+"/";
   }
    
  }
  return string2;
 }
}    这里就介绍使用ajaxFileUpload异步上传文件。下面将介绍如何截取头像(类似于QQ上传头像)


 

觉得可用,就经常来吧! 脚本宝典 欢迎评论哦! js脚本,巧夺天工,精雕玉琢。小宝典献丑了!

脚本宝典总结

以上是脚本宝典为你收集整理的javascript代码实例教程-jquery之ajaxfileupload异步上传插件全部内容,希望文章能够帮你解决javascript代码实例教程-jquery之ajaxfileupload异步上传插件所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。