Java利用jQuery的ajaxFileUpload异步上传文件的几种方式

本文详细介绍了如何使用jQuery的ajaxFileUpload插件进行异步文件上传,包括SSH2项目中的应用、Struts2和SpringMVC的集成,以及解决上传过程中遇到的各种错误。通过实例代码展示了在不同场景下的文件上传配置和处理,涵盖了上传文件的前端、后端处理和异常情况。同时,强调了上传文件时的注意事项,如文件域的name属性、dataType大小写敏感等关键点。
摘要由CSDN通过智能技术生成

ajaxFileUpload实现异步上传文件

一、ajaxFileUpload是一个异步上传文件的jQuery插件。

  传一个不知道什么版本的上来,以后不用到处找了。

  语法:$.ajaxFileUpload([options])

  options参数说明:

1、url            上传处理程序地址。  
2,fileElementId       需要上传的文件域的ID,即<input type="file">的ID。
3,secureuri        是否启用安全提交,默认为false。 
4,dataType        服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
5,success        提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
6,error          提交失败自动执行的处理函数。
7,data           自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。
8, type            当要提交自定义参数时,这个参数要设置成post

错误提示:

1,SyntaxError: missing ; before statement错误
  如果出现这个错误就需要检查url路径是否可以访问
2,SyntaxError: syntax error错误
  如果出现这个错误就需要检查处理提交操作的服务器后台处理程序是否存在语法错误
3,SyntaxError: invalid property id错误
  如果出现这个错误就需要检查文本域属性ID是否存在
4,SyntaxError: missing } in XML expression错误
  如果出现这个错误就需要检查文件name是否一致或不存在
5,其它自定义错误
  大家可使用变量$error直接打印的方法检查各参数是否正确,比起上面这些无效的错误提示还是方便很多。

 

  使用方法:

  第一步:先引入jQuery与ajaxFileUpload插件。注意先后顺序,这个不用说了,所有的插件都是这样。

    <script src="jquery-1.7.1.js" type="text/javascript"></script>
    <script src="ajaxfileupload.js" type="text/javascript"></script>

  第二步:HTML代码:

<body>
    <p><input type="file" id="file1" name="file" /></p>
    <input type="button" value="上传" />
    <p><img id="img1" alt="上传成功啦,你妈个B啦" src="" /></p>
</body>

  第三步:JS代码

复制代码
    <script src="jquery-1.7.1.js" type="text/javascript"></script>
    <script src="ajaxfileupload.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $(":button").click(function () {
                ajaxFileUpload();
            })
        })
        function ajaxFileUpload() {
            $.ajaxFileUpload
            (
                {
                    url: '/upload.aspx', //用于文件上传的服务器端请求地址
                    secureuri: false, //是否需要安全协议,一般设置为false
                    fileElementId: 'file1', //文件上传域的ID
                    dataType: 'json', //返回值类型 一般设置为json
                    success: function (data, status)  //服务器成功响应处理函数
                    {
                        $("#img1").attr("src", data.imgurl);
                        if (typeof (data.error) != 'undefined') {
                            if (data.error != '') {
                                alert(data.error);
                            } else {
                                alert(data.msg);
                            }
                        }
                    },
                    error: function (data, status, e)//服务器响应失败处理函数
                    {
                        alert(e);
                    }
                }
            )
            return false;
        }
    </script>
复制代码

    第四步:后台页面upload.aspx代码:

复制代码
        protected void Page_Load(object sender, EventArgs e)
        {
            HttpFileCollection files = Request.Files;
            string msg = string.Empty;
            string error = string.Empty;
            string imgurl;
            if (files.Count > 0)
            {
                files[0].SaveAs(Server.MapPath("/") + System.IO.Path.GetFileName(files[0].FileName));
                msg = " 成功! 文件大小为:" + files[0].ContentLength;
                imgurl = "/" + files[0].FileName;
                string res = "{ error:'" + error + "', msg:'" + msg + "',imgurl:'" + imgurl + "'}";
                Response.Write(res);
                Response.End();
            }
        }
复制代码

  本实例完整代码下载

来一个MVC版本的实例:

控制器代码

复制代码
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Upload()
        {
            HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            string imgPath = "";
            if (hfc.Count > 0)
            {
                imgPath = "/testUpload" + hfc[0].FileName;
                string PhysicalPath = Server.MapPath(imgPath);
                hfc[0].SaveAs(PhysicalPath);
            }
            return Content(imgPath);
        }
    }
复制代码

 

前端视图,HTML与JS代码,成功上传后,返回图片真实地址并绑定到<img>的SRC地址

复制代码
<html>
<head>
    <script src="/jquery-1.7.1.js" type="text/javascript"></script>
    <script src="/ajaxfileupload.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $(":button").click(function () {
                if ($("#file1").val().length > 0) {
                    ajaxFileUpload();
                }
                else {
                    alert("请选择图片");
                }
            })
        })
        function ajaxFileUpload() {
            $.ajaxFileUpload
            (
                {
                    url: '/Home/Upload', //用于文件上传的服务器端请求地址
                    secureuri: false, //一般设置为false
                    fileElementId: 'file1', //文件上传空间的id属性  <input type="file" id="file" name="file" />
                    dataType: 'HTML', //返回值类型 一般设置为json
                    success: function (data, status)  //服务器成功响应处理函数
                    {
                        alert(data);
                        $("#img1").attr("src", data);
                        if (typeof (data.error) != 'undefined') {
                            if (data.error != '') {
                                alert(data.error);
                            } else {
                                alert(data.msg);
                            }
                        }
                    },
                    error: function (data, status, e)//服务器响应失败处理函数
                    {
                        alert(e);
                    }
                }
            )
            return false;
        }
    </script>
</head>
<body>
    <p><input type="file" id="file1" name="file" /></p>
    <input type="button" value="上传" />
    <p><img id="img1" alt="上传成功啦,你妈个B啦" src="" /></p>
</body>
</html>
复制代码

 最后再来一个上传图片且附带参数的实例:控制器代码:

复制代码
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Upload()
        {
            NameValueCollection nvc = System.Web.HttpContext.Current.Request.Form;

            HttpFileCollection hfc = System.Web.HttpContext.Current.Request.Files;
            string imgPath = "";
            if (hfc.Count > 0)
            {
                imgPath = "/testUpload" + hfc[0].FileName;
                string PhysicalPath = Server.MapPath(imgPath);
                hfc[0].SaveAs(PhysicalPath);
            }
            //注意要写好后面的第二第三个参数
            return Json(new { Id = nvc.Get("Id"), name = nvc.Get("name"), imgPath1 = imgPath },"text/html", JsonRequestBehavior.AllowGet);
        }
    }
复制代码

Index视图代码:

复制代码
<html>
<head>
    <script src="/jquery-1.7.1.js" type="text/javascript"></script>
    <script src="/ajaxfileupload.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $(":button").click(function () {
                if ($("#file1").val().length > 0) {
                    ajaxFileUpload();
                }
                else {
                    alert("请选择图片");
                }
            })
        })
        function ajaxFileUpload() {
            $.ajaxFileUpload
            (
                {
                    url: '/Home/Upload', //用于文件上传的服务器端请求地址
                    type: 'post',
                    data: { Id: '123', name: 'lunis' }, //此参数非常严谨,写错一个引号都不行
                    secureuri: false, //一般设置为false
                    fileElementId: 'file1', //文件上传空间的id属性  <input type="file" id="file" name="file" />
                    dataType: 'json', //返回值类型 一般设置为json
                    success: function (data, status)  //服务器成功响应处理函数
                    {
                        alert(data);
                        $("#img1").attr("src", data.imgPath1);
                        alert("你请求的Id是" + data.Id + "     " + "你请求的名字是:" + data.name);
                        if (typeof (data.error) != 'undefined') {
                            if (data.error != '') {
                                alert(data.error);
                            } else {
                                alert(data.msg);
                            }
                        }
                    },
                    error: function (data, status, e)//服务器响应失败处理函数
                    {
                        alert(e);
                    }
                }
            )
            return false;
        }
    </script>
</head>
<body>
    <p><input type="file" id="file1" name="file" /></p>
    <input type="button" value="上传" />
    <p><img id="img1" alt="上传成功啦,你妈个B啦" src="" /></p>
</body>
</html>
复制代码

此实例在显示出异步上传图片的同时并弹出自定义传输的参数。本实例下载地址

 

  2013年1月28日,今天调试过程中发现一个问题,就是作为文件域(<input type="file">)必须要有name属性,如果没有name属性,上传之后服务器是获取不到图片的。如:正确的写法是<input type="file" id="file1" name="file1" />

  2013年1月28日,最经典的错误终于找到原因所在了。Object function (a,b){return new e.fn.init(a,b,h)} has no method 'handleError',这个是google浏览器报的错误,非常经典, 不知道是我的版本问题还是真正存在的问题。这个问题的根源经过N次上传才找到问题的根本所在。答案是:dataType参数一定要大写。如:dataType: 'HTML'。


1.SSH2下使用ajaxFileUpload控件上传附件

使用jQuery的ajaxFileUpload控件以ajax方式上传附件有较好的用户体验,在某SSH2项目开发中,使用了ajaxFileUpload实现了附件的上传,具体过程如下:

1、引入及修改ajaxFileUpload.js

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <script type="text/javascript" src="<%=basePath%>/js/jquery/jquery-1.8.0.min.js"></script>  
  2. <script type="text/javascript" src="<%=basePath%>js/ajaxfileupload.js"></script>   

为了使得ajaxfileupload支持IE9、IE10,在ajaxfileupload.js中修改createUploadIframe方法(可参考 http://blog.csdn.net/tiangsu_php/article/details/7795927

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1.  createUploadIframe: function(id, uri)  
  2.     {  
  3.             //create frame  
  4.             var frameId = 'jUploadFrame' + id;          
  5.             if(window.ActiveXObject) {   
  6.                 if(jQuery.browser.version=="9.0"||jQuery.browser.version=="10.0") {   
  7.                     io = document.createElement('iframe');   
  8.                     io.id = frameId;   
  9.                     io.name = frameId;   
  10.                 } else if(jQuery.browser.version=="6.0"||jQuery.browser.version=="7.0"||jQuery.browser.version=="8.0") {   
  11.                     var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');   
  12.                     if(typeof uri== 'boolean'){   
  13.                         io.src = 'javascript:false';   
  14.                     }   
  15.                     else if(typeof uri== 'string'){   
  16.                         io.src = uri;   
  17.                     }      
  18.                 }   
  19. }   


2、form表单及上传控件

form表单设置为:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. enctype="multipart/form-data" id="addForm" method="post"  
上传控件代码为:
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <input id="upload" name="upload" size="50"   type="file"  />    
  2. <a class="easyui-linkbutton" iconCls="icon-upload" onclick="ajaxFileUploadCheckType('/sys/file/uploadSysFile.action?fileVo.status=0')" >上传</a>  
  3.  <img src="<%=basePath%>/img/loading_16x16.gif" id="loading"    style="display: none;">                          
  4.    
上传的脚本代码为:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1.     function ajaxFileUploadCheckType(url){        
  2.          var str="";      
  3.          var re=new RegExp("(.pdf|.PDF)$");  
  4.              var upload=$("#upload").val();      
  5.          if(upload=="")         
  6.                str+="请选择要上传的附件!<br/>";   
  7.              else if(!re.test(upload.toLowerCase()))  
  8.                str+="请上传PDF格式的文件!!";      
  9.          if(str=="")  
  10.                 ajaxFileUpload(url);  
  11.           else  
  12.                 alert(str);       
  13.     }  
  14.         //文件上传  
  15.         function ajaxFileUpload(url1)  
  16.             {  
  17.               $("#loading")  
  18.                 .ajaxStart(function(){  
  19.                     $(this).show();  
  20.                 })//开始上传文件时显示一个等待图片  
  21.                 .ajaxComplete(function(){      
  22.                     $(this).hide();  
  23.                 });//文件上传完成将图片隐藏起来  
  24.                 var fileSelect=$("#fileSelect").val(); //是否选择了文件类型  
  25.                 var url2=url1;  
  26.                 if(fileSelect!=undefined&&fileSelect!=null&&fileSelect!=''){  
  27.                 if(url1.indexOf('?')>0)  
  28.                   url2=encodeURI(url1+"&fileVo.fileTypeId="+fileSelect);  
  29.                 else  
  30.                   url2=encodeURI(url1+"?fileVo.fileTypeId="+fileSelect);    
  31.                 }   
  32.                 var tableName=$("#tableName").val();       
  33.                 if(url2.indexOf('?')>0)  
  34.                      url2=encodeURI(url2+"&fileVo.tableName="+tableName);  
  35.                 else  
  36.                     url2=encodeURI(url2+"?fileVo.tableName="+tableName);  
  37.                 var fid=$("#fid").val();  
  38.                 if(url2.indexOf('?')>0)  
  39.                      url2=encodeURI(url2+"&fileVo.fid="+fid);  
  40.                 else    
  41.                     url2=encodeURI(url2+"?fileVo.fid="+fid);                
  42.                 $.ajaxFileUpload     
  43.                 (                       
  44.                     {           
  45.                         url:url2,//用于文件上传的服务器端请求地址       
  46.                         secureuri:false,//一般设置为false  
  47.                         fileElementId:'upload',//文件上传空间的id属性  <input type="file" id="upload" name="upload" />                        
  48.                         // type:'POST',    
  49.                         dataType: 'text',//返回值类型 一般设置为json       
  50.                         //contentType: "application/x-www-form-urlencoded; charset=utf-8",  
  51.                         success: function (data, status)  //服务器成功响应处理函数  
  52.                         {                                    
  53.                            //alert((data));                 
  54.                             var result=eval('('+data+')');        
  55.                             generateFileList(result,"type"); //使用ajax方式重新长生附件列表                             
  56.                                                               
  57.                         },  
  58.                         error: function (data, status, e)//服务器响应失败处理函数  
  59.                         {        
  60.                             $.messager.alert('错误提示',"文件上传出现异常,请重新上传或联系管理员!","error");  
  61.                         }  
  62.                     }  
  63.                 )              
  64.                 return false;  
  65.             }  
  66.         

 3、Struts2的XML配置及服务器端处理

XML配置:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1.      <package name="sys.file" namespace="/sys/file" extends="globalpackage">  
  2. lt;action name="uploadSysFile" class="com.cnpc.sys.action.FileUploadAction"  
  3. method="uploadSysFile">  
  4. lt;/action>  
  5.       ……  

服务器端Action处理:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.cnpc.sys.action;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.FileOutputStream;  
  6. import java.io.IOException;  
  7. import java.util.ArrayList;  
  8. import java.util.Date;  
  9. import java.util.List;  
  10.   
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. import org.apache.struts2.ServletActionContext;  
  15.   
  16. import com.cnpc.framework.common.action.BaseAction;  
  17. import com.cnpc.framework.common.exception.GlobalException;  
  18. import com.cnpc.framework.common.servicefactory.SystemInstance;  
  19. import com.cnpc.sys.entity.Dictionary;  
  20. import com.cnpc.sys.entity.Employee;  
  21. import com.cnpc.sys.service.IDictionaryService;  
  22. import com.cnpc.sys.service.IEmployeeService;  
  23. import com.cnpc.sys.service.ISysFileService;  
  24. import com.cnpc.sys.vo.SysFileVo;  
  25. import com.cnpc.utils.DateUtils;  
  26. import com.cnpc.utils.PropertiesTools;  
  27. import com.cnpc.utils.StrUtils;  
  28.   
  29.   
  30. //附件上传处理类  
  31. public class FileUploadAction extends BaseAction {  
  32.     private ISysFileService sysFileService = (ISysFileService) SystemInstance  
  33.             .getInstance().getBean(ISysFileService.class);  
  34.     private IDictionaryService dictionaryService = (IDictionaryService) SystemInstance  
  35.             .getInstance().getBean(IDictionaryService.class);  
  36.     private IEmployeeService employeeService = (IEmployeeService) SystemInstance  
  37.     .getInstance().getBean(IEmployeeService.class);  
  38.     private SysFileVo fileVo;  
  39.     private File upload;// 实际上传文件  
  40.     private String uploadContentType; // 文件的内容类型  
  41.     private String uploadFileName; // 上传文件名  
  42.     private List<SysFileVo> fileVoList;  
  43.     private String message = "你已成功上传文件";  
  44.     private String tableName;  
  45.     private String year;  
  46.     private List<SysFileVo> volist;  
  47.   
  48.       
  49.       
  50.     public String getYear() {  
  51.         return year;  
  52.     }  
  53.   
  54.     public void setYear(String year) {  
  55.         this.year = year;  
  56.     }  
  57.   
  58.     public String getTableName() {  
  59.         return tableName;  
  60.     }  
  61.   
  62.     public void setTableName(String tableName) {  
  63.         this.tableName = tableName;  
  64.     }  
  65.   
  66.     public List<SysFileVo> getVolist() {  
  67.         return volist;  
  68.     }  
  69.   
  70.     public void setVolist(List<SysFileVo> volist) {  
  71.         this.volist = volist;  
  72.     }  
  73.   
  74.     public SysFileVo getFileVo() {  
  75.         return fileVo;  
  76.     }  
  77.   
  78.     public void setFileVo(SysFileVo fileVo) {  
  79.         this.fileVo = fileVo;  
  80.     }  
  81.   
  82.     public File getUpload() {  
  83.         return upload;  
  84.     }  
  85.   
  86.     public void setUpload(File upload) {  
  87.         this.upload = upload;  
  88.     }  
  89.   
  90.     public String getUploadContentType() {  
  91.         return uploadContentType;  
  92.     }  
  93.   
  94.     public void setUploadContentType(String uploadContentType) {  
  95.         this.uploadContentType = uploadContentType;  
  96.     }  
  97.   
  98.     public String getUploadFileName() {  
  99.         return uploadFileName;  
  100.     }  
  101.   
  102.     public void setUploadFileName(String uploadFileName) {  
  103.         this.uploadFileName = uploadFileName;  
  104.     }  
  105.   
  106.     public List<SysFileVo> getFileVoList() {  
  107.         return fileVoList;  
  108.     }  
  109.   
  110.     public void setFileVoList(List<SysFileVo> fileVoList) {  
  111.         this.fileVoList = fileVoList;  
  112.     }  
  113.   
  114.     public String getMessage() {  
  115.         return message;  
  116.     }  
  117.   
  118.     public void setMessage(String message) {  
  119.         this.message = message;  
  120.     }  
  121.   
  122.     public String uploadSysFile() throws GlobalException, IOException {  
  123.         String isAll=fileVo.getIsAll();  
  124.         Employee emp = employeeService.getEmployeeByID(getSessionContainer().getUserId());  
  125.         if (fileVo == null) {    
  126.             fileVo = new SysFileVo();     
  127.         }       
  128.         String[] str = saveUpload();  
  129.         fileVo.setFileName(str[0]);  
  130.         fileVo.setVirtualName(str[1]);  
  131.         fileVo.setFilePath(str[2].replace("\\", "\\\\"));  
  132.         if (fileVo != null) {  
  133.   
  134.             if (fileVo.getEmpid() == null) {         
  135.                 Integer empid = emp.getEmpid();  
  136.                 fileVo.setEmpid(empid);  
  137.             }  
  138.             if (fileVo.getUploadTime() == null) {  
  139.                 fileVo.setUploadTime(DateUtils.format(new Date(System  
  140.                         .currentTimeMillis()), DateUtils.formatStr_yyyyMMdd));  
  141.             }  
  142.             if (fileVo.getTableName() == null) {  
  143.                 fileVo.setTableName(tableName);  
  144.             }  
  145.             if(fileVo.getYear()==null){  
  146.                 if(year==null)  
  147.                     year=DateUtils.getYear();     
  148.                 fileVo.setYear(year);  
  149.             }  
  150.             if(fileVo.getIid()==null){  
  151.                 fileVo.setIid(emp.getInstitute().getIid());   
  152.             }             
  153.             fileVo = sysFileService.addSysFileVo(fileVo);  
  154.         }  
  155.         if (fileVoList == null) {  
  156.             fileVoList = new ArrayList<SysFileVo>();  
  157.         }       
  158.         fileVo.setIsAll(isAll);  
  159.         if(fileVo.getIsAll()!=null&&fileVo.getIsAll().equals("1")){  
  160.             fileVoList = sysFileService.getAllSysFileByInfoId(  
  161.                     fileVo.getTableName(), fileVo.getFid());          
  162.         }else{  
  163.             fileVoList = sysFileService.getSysFileByInfoId(  
  164.                     fileVo.getTableName(),null, fileVo.getFid(),fileVo.getStatus());   
  165.         }  
  166.         String jsonStr = getJsonForFileList(fileVoList);  
  167.         HttpServletResponse response = getCurrentResponse();  
  168.         HttpServletRequest request=getCurrentRequest();  
  169.         request.setCharacterEncoding(ENCODING);  
  170.         response.setCharacterEncoding(ENCODING);  
  171.         response.setContentType("text/html");    
  172.         outPutString(jsonStr);           
  173.         return NONE;    
  174.     }  
  175.   
  176.       
  177.   
  178.     public String getJsonForFileList(List<SysFileVo> filelist) {  
  179.         if (filelist == null)  
  180.             return "[]";  
  181.         StringBuffer buffer = new StringBuffer("[");  
  182.         for (SysFileVo vo : filelist) {  
  183.             buffer.append("{'id':'" + vo.getFileId() + "' ,'name':'"  
  184.                     + vo.getFileName() + "','path':'"  
  185.                     + vo.getFilePath().replace("\\", "\\\\") + "','typeName':'"  
  186.                     + vo.getFileTypeName() + "','typeid':'"  
  187.                     + vo.getFileTypeId() + "','status':'"  
  188.                     + vo.getStatus() + "'},");           
  189.         }  
  190.         if (buffer.length() > 1)  
  191.             buffer = new StringBuffer(buffer.substring(0, buffer.length() - 1));  
  192.         buffer.append("]");    
  193.         return buffer.toString();  
  194.     }  
  195.   
  196.     @SuppressWarnings("deprecation")  
  197.     public String[] saveUpload() throws IOException {  
  198.         String[] result = new String[3];  
  199.         try {  
  200.             if (uploadFileName != null && !"".equals(uploadFileName)) {  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值