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

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
  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
  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
  1. enctype="multipart/form-data" id="addForm" method="post"  
上传控件代码为:
[html]  view plain copy
  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
  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
  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
  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)) {  
  201.                 String trueName = uploadFileName.substring(uploadFileName  
  202.                         .lastIndexOf("/") + 1, uploadFileName.length());  
  203.                 String fileName = new Date().getTime()  
  204.                         + com.cnpc.utils.FileUtils.getExtention(uploadFileName);  
  205.                 String path = PropertiesTools.getPropertiesValueByFileAndKey(  
  206.                         "globalParameters.properties", "uploadPath");  
  207.                 String targetDirectory = path;  
  208.                 String targetFileName = fileName;  
  209.                 // 以服务器的文件保存地址和原文件名建立上传文件输出流  
  210.                 FileOutputStream fos = new FileOutputStream(path + "\\"  
  211.                         + fileName);  
  212.                 // 以上传文件建立一个文件上传流  
  213.                 FileInputStream fis = new FileInputStream(upload);  
  214.                 // 将上传文件的内容写入服务器  
  215.                 byte[] buffer = new byte[1024];  
  216.                 int len = 0;  
  217.                 while ((len = fis.read(buffer)) > 0) {  
  218.                     fos.write(buffer, 0, len);  
  219.                 }  
  220.                 fis.close();  
  221.                 fos.flush();  
  222.   
  223.                 result[0] = trueName;  
  224.                 result[1] = fileName;  
  225.                 result[2] = path + "\\" + fileName;  
  226.             }  
  227.         } catch (Exception e) {  
  228.             e.printStackTrace();  
  229.             message = "对不起,文件上传失败了!!!!";  
  230.         }  
  231.         return result;  
  232.     }  
  233.   
  234.     public String deleteSysFile() throws GlobalException, IOException {       
  235.         if (fileVo != null && fileVo.getFileId() != null) {  
  236.             SysFileVo deleteVo = sysFileService.getSysFileByID(fileVo  
  237.                     .getFileId());  
  238.             deleteFile(deleteVo.getFilePath());        
  239.             sysFileService.deleteSysFileByVoId(deleteVo.getFileId());  
  240.             if (fileVoList == null) {      
  241.                 fileVoList = new ArrayList<SysFileVo>();  
  242.             }  
  243.             if(fileVo.getIsAll()!=null&&fileVo.getIsAll().equals("1")){  
  244.                 fileVoList = sysFileService.getAllSysFileByInfoId(      
  245.                         deleteVo.getTableName(), deleteVo.getFid());              
  246.             }else{            
  247.                 fileVoList = sysFileService.getSysFileByInfoId(deleteVo.getTableName(),null, deleteVo.getFid(),deleteVo.getStatus());   
  248.             }  
  249.         }  
  250.         String jsonStr = getJsonForFileList(fileVoList);  
  251.         HttpServletResponse response = getCurrentResponse();  
  252.         HttpServletRequest request=getCurrentRequest();  
  253.         request.setCharacterEncoding(ENCODING);  
  254.         response.setCharacterEncoding(ENCODING);  
  255.         response.setContentType("text/html");    
  256.         outPutString(jsonStr);  
  257.         return NONE;  
  258.     }  
  259.   
  260.       
  261.   
  262.     public String downloadFile() throws Exception {  
  263.         SysFileVo filevo = sysFileService  
  264.                 .getsysfilebypath(fileVo.getFilePath());  
  265.         HttpServletResponse response = getCurrentResponse();  
  266.         HttpServletRequest request=getCurrentRequest();  
  267.         request.setCharacterEncoding(ENCODING);  
  268.         response.setCharacterEncoding(ENCODING);     
  269.         response.setContentType("text/html");    
  270.         if (filevo != null) {  
  271.             setCurrentAttribute("filename", filevo.getFileName());  
  272.             setCurrentAttribute("fileurl", filevo.getFilePath());  
  273.         } else {  
  274.             setCurrentAttribute("filename", fileVo.getFileName());  
  275.             setCurrentAttribute("fileurl", fileVo.getFilePath());  
  276.         }  
  277.         return "download";  
  278.     }  
  279.   
  280.     public void deleteFile(String path) {  
  281.         String targetDirectory = ServletActionContext.getRequest().getRealPath(  
  282.                 "");  
  283.         File target = new File(targetDirectory, path);  
  284.         if (target.exists()) {  
  285.             target.delete();  
  286.         } else {  
  287.             System.out.println("文件不存在");  
  288.         }  
  289.     }  
  290.   
  291.     public String ajaxCheckFile() throws IOException {  
  292.         String typeids = getCurrentParameter("typeids");  
  293.         String dictCode = getCurrentParameter("dictCode");  
  294.         // List<SysFileVo> filelist=sysFileService.getSysFileByInfoId(tabName,  
  295.         // Integer.valueOf(id));  
  296.         String[] arrType = null;  
  297.         if (!StrUtils.isEmpty(typeids))  
  298.             arrType = typeids.substring(0, typeids.length() - 1).split(",");  
  299.         List<Dictionary> dictlist = dictionaryService  
  300.                 .getDictsByDictCode(dictCode);  
  301.         String str = "";  
  302.         boolean isExist = false;  
  303.         for (Dictionary dict : dictlist) {  
  304.             isExist = false;  
  305.             if (dict.getIsCheck() != null && dict.getIsCheck().equals("1")) {  
  306.                 if (arrType != null) {  
  307.                     for (String typeid : arrType) {  
  308.                         if (dict.getDictid().equals(Integer.valueOf(typeid))) {  
  309.                             isExist = true;  
  310.                             break;  
  311.                         }        
  312.                     }  
  313.                 }  
  314.                 if (!isExist)  
  315.                     str += dict.getDictName() + "不能为空!\r\n";  
  316.             }  
  317.         }  
  318.         outPutString(str);  
  319.         return NONE;  
  320.     }  
  321.   
  322. }  

FileUploadAction包含了附件上传、删除、生成json附件列表功能,该处理类是直接复制、粘贴项目源代码而来,如果使用,请按照需求进行增删。


以上三个步骤就在SSH2中完成了ajaxFileUpload控件上传附件的功能,仅供参考。


2.AjaxFileUpload组件结合Struts2异步图片上传

使用AjaxFileUpload组件结合Struts2异步上传需要添加如下文件:

ajaxfileupload.js

jquery-x.x.x-min.js

struts2相关jar包

AjaxFileUpload组件下载连接:http://download.csdn.net/detail/yangfuqian/4337967

具体实现代码:

服务端:

[html]  view plain copy
  1. package com.tenghu.action.upload;  
  2. import java.io.File;  
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.InputStream;  
  6. import java.io.OutputStream;  
  7. import javax.servlet.http.HttpServletRequest;  
  8.   
  9. import org.apache.struts2.ServletActionContext;  
  10. import com.opensymphony.xwork2.ActionSupport;  
  11. /**  
  12.  * 文件上传Action  
  13.  * @author xiaohu  
  14.  *  
  15.  */  
  16. public class FileUpload extends ActionSupport{  
  17.     private String name;  
  18.     //封装上传文件域的属性  
  19.     private File file;  
  20.     //封装上传文件类型的属性  
  21.     private String fileContentType;  
  22.     //封装上传文件名的属性  
  23.     private String fileFileName;  
  24.     //提示信息  
  25.     private String json_message;  
  26.       
  27.     private String JSON_MESSAGE="json_message";  
  28.       
  29.     @Override  
  30.     public String execute() throws Exception {  
  31.         try {  
  32.             //设置文件保存目录  
  33.             String saveDir=getRootPath()+"/images";  
  34.             File saveFile=new File(saveDir);  
  35.             //判断  
  36.             if(!saveFile.exists()){  
  37.                 saveFile.mkdirs();  
  38.             }  
  39.             //时间戳  
  40.             String timeStr="zycs"+System.currentTimeMillis();  
  41.             //获取文件后缀  
  42.             String fileSuffix=fileFileName.substring(fileFileName.indexOf("."));  
  43.             //拼接文件名  
  44.             String fileName=timeStr+fileSuffix;  
  45.             //创建文件输出流对象  
  46.             OutputStream fos=new FileOutputStream(saveDir+"/"+fileName);  
  47.             //创建文件输入流对象  
  48.             InputStream fis=new FileInputStream(file);  
  49.             //创建缓冲数组  
  50.             byte[] buffer=new byte[1024];  
  51.             int len=0;  
  52.             //从输入流中将数据写入到输出流中  
  53.             while((len=fis.read(buffer))!=-1){  
  54.                 //写入  
  55.                 fos.write(buffer,0,len);  
  56.             }  
  57.             //关闭资源  
  58.             fis.close();  
  59.             fos.close();  
  60.             //上传成功地址  
  61.             String successPath=getUrl()+"/images/"+fileName;  
  62.             json_message="{\"result\":1,\"message\":\""+successPath+"\"}";  
  63.         } catch (Exception e) {  
  64.             e.printStackTrace();  
  65.             json_message="{\"result\":0}";  
  66.         }  
  67.         return JSON_MESSAGE;  
  68.     }  
  69.     /**  
  70.      * 返回服务器http地址  
  71.      * @return  
  72.      */  
  73.     private String getUrl(){  
  74.         HttpServletRequest request=ServletActionContext.getRequest();  
  75.         return "http://"+request.getRemoteHost()+request.getContextPath();  
  76.     }  
  77.       
  78.     /**  
  79.      * 获取项目根目录  
  80.      * @return  
  81.      */  
  82.     private String getRootPath(){  
  83.         String filePath = Thread.currentThread().getContextClassLoader()  
  84.                 .getResource("").toString();  
  85.         if (filePath.toLowerCase().indexOf("file:") > -1) {  
  86.             filePath = filePath.substring(6, filePath.length());  
  87.         }  
  88.         if (filePath.toLowerCase().indexOf("classes") > -1) {  
  89.             filePath = filePath.replaceAll("/classes", "");  
  90.         }  
  91.         if (filePath.toLowerCase().indexOf("web-inf") > -1) {  
  92.             filePath = filePath.substring(0, filePath.length() - 9);  
  93.         }  
  94.         if (System.getProperty("os.name").toLowerCase().indexOf("window") < 0) {  
  95.             filePath = "/" + filePath;  
  96.         }  
  97.   
  98.         if (filePath.endsWith("/"))  
  99.             filePath = filePath.substring(0, filePath.length() - 1);  
  100.   
  101.         return filePath;  
  102.     }  
  103.   
  104.     public String getName() {  
  105.         return name;  
  106.     }  
  107.   
  108.     public void setName(String name) {  
  109.         this.name = name;  
  110.     }  
  111.   
  112.     public File getFile() {  
  113.         return file;  
  114.     }  
  115.   
  116.     public void setFile(File file) {  
  117.         this.file = file;  
  118.     }  
  119.   
  120.     public String getFileContentType() {  
  121.         return fileContentType;  
  122.     }  
  123.   
  124.     public String getJson_message() {  
  125.         return json_message;  
  126.     }  
  127.     public void setJson_message(String jsonMessage) {  
  128.         json_message = jsonMessage;  
  129.     }  
  130.     public void setFileContentType(String fileContentType) {  
  131.         this.fileContentType = fileContentType;  
  132.     }  
  133.   
  134.     public String getFileFileName() {  
  135.         return fileFileName;  
  136.     }  
  137.   
  138.     public void setFileFileName(String fileFileName) {  
  139.         this.fileFileName = fileFileName;  
  140.     }  
  141. }  

如果希望获取到上传图片的宽和高,可以添加以下代码:

[html]  view plain copy
  1. //获取图片缓冲流对象  
  2.             BufferedImage image=ImageIO.read(fis);  
  3.             image.getWidth();//图片宽  
  4.             image.getHeight();//图片高  
这里的fis表示:InputStream输入流,也可以直接传入File文件对象

js代码:

[html]  view plain copy
  1. <script type="text/javascript">  
  2.     $(document).ready(function() {  
  3.         //调用初始化方法  
  4.             UPLOAD.init();  
  5.         });  
  6.   
  7.     var UPLOAD = {  
  8.         wWidth : $(window).width(),//获取浏览器可视化宽度  
  9.         wHeight : $(window).height(),//获取浏览器可视化高度  
  10.         //初始化上传文件窗口的位置  
  11.         init : function() {  
  12.             //获取窗口div对象  
  13.             var uObj = $(".w_sub");  
  14.             //设置上传窗口位置  
  15.             uObj.css( {"left" : (this.wWidth - uObj.width()) / 2,"top" : (this.wHeight - uObj.height()) / 2});  
  16.             //点击上传按钮显示上传窗口  
  17.             $("#upload").click(function(){$("#upload_w").show();});  
  18.               
  19.             //调用关闭窗口  
  20.             this.closeUp();  
  21.             //调用关闭预览窗口  
  22.             this.closePre();  
  23.             //调用上传函数  
  24.             this.btnUpload();  
  25.             //调用预览图片  
  26.             this.btnPreview();  
  27.             this.dragDrop();  
  28.               
  29.         },  
  30.         //关闭上传窗口  
  31.         closeUp:function(){  
  32.             $(".close").click(function(){$("#upload_w").hide();});  
  33.         },  
  34.         //关闭预览窗口  
  35.         closePre:function(){  
  36.             $(".pre").click(function(){$(".preview_w").hide();});  
  37.         },//点击上传  
  38.         btnUpload:function(){  
  39.             $(".sub_upload").click(function(){  
  40.                 var file=$("#file").val();  
  41.                 if(file==""){  
  42.                     alert("请选择需要上传的图片");  
  43.                     return;  
  44.                 }else{  
  45.                     //判断上传文件格式  
  46.                     var suffixs=new Array("jpg","gif","png");  
  47.                     //截取上传文件格式  
  48.                     var fileType=file.substring(file.lastIndexOf('.')+1);  
  49.                     if($.inArray(fileType,suffixs)<=-1){  
  50.                         alert("图片格式错误");  
  51.                         return;  
  52.                     }else{  
  53.                         var uploadUrl="uploadFile?time="+new Date().getTime();  
  54.                         //异步上传  
  55.                         $.ajaxFileUpload({  
  56.                             url:uploadUrl,  
  57.                             secureuri:false,  
  58.                             fileElementId:"file",//上传id,这里是<input type="file" name="file" id="file"/>  
  59.                             dataType:'text',  
  60.                             success:function(data,status){  
  61.                                 var json=$.parseJSON(data);  
  62.                                 if(json.result==1){  
  63.                                     $("#upload_w").hide();  
  64.                                     $(".url").val(json.message);  
  65.                                 }else{  
  66.                                     alert("上传失败!");  
  67.                                 }  
  68.                                   
  69.                             },  
  70.                             error:function(){  
  71.                                 alert("异步失败");  
  72.                             }  
  73.                         });  
  74.                     }  
  75.                 }  
  76.             });  
  77.         },  
  78.         //点击预览  
  79.         btnPreview:function(){  
  80.             //点击预览图片  
  81.             $("#proview_img").click(function(){  
  82.                 //获取文本框中的路径  
  83.                 var imagePath=$(".url").val();  
  84.                 if(imagePath!=""){  
  85.                     $("#image").attr("src",$(".url").val());  
  86.                     $(".preview_w").show();  
  87.                 }else{  
  88.                     alert("还有上传图片");  
  89.                 }  
  90.             });  
  91.         },  
  92.         /**  
  93.         *拖拽弹窗  
  94.         */  
  95.         dragDrop:function(){  
  96.             var self=this;  
  97.             var move=false;//标识是否移动元素  
  98.             var offsetX=0;//弹窗到浏览器left的宽度  
  99.             var offsetY=0;//弹出到浏览器top的宽度  
  100.             var title=$(".title");  
  101.             boxContent=$(".preview");  
  102.             //鼠标按下事件  
  103.             title.mousedown(function(){  
  104.                 move=true;//当鼠标按在该div上的时间将move属性设置为true  
  105.                 offsetX=event.offsetX;//获取鼠标在当前窗口的相对偏移位置的Left值并赋值给offsetX  
  106.                 offsetY=event.offsetY;//获取鼠标在当前窗口的相对偏移位置的Top值并赋值给offsetY  
  107.                 title.css({"cursor":"move"});  
  108.             }).mouseup(function(){  
  109.                 //当鼠标松开的时候将move属性摄hi为false  
  110.                 move=false;  
  111.             });  
  112.             $(document).mousemove(function(){  
  113.                 if(!move){//如果move属性不为true,就不执行下面的代码  
  114.                     return;  
  115.                 }  
  116.                 //move为true的时候执行下面代码  
  117.                 var x = event.clientX-offsetX; //event.clientX得到鼠标相对于客户端正文区域的偏移,然后减去offsetX即得到当前推拽元素相对于当前窗口的X值(减去鼠标刚开始拖动的时候在当前窗口的偏移X)  
  118.                 var y = event.clientY-offsetY; //event.clientY得到鼠标相对于客户端正文区域的偏移,然后减去offsetX即得到当前推拽元素相对于当前窗口的Y值(减去鼠标刚开始拖动的时候在当前窗口的偏移Y)  
  119.                 if(!(x<0||y<0||x>(self.wWidth-boxContent.width())||y>(self.wHeight-boxContent.height()))){  
  120.                     boxContent.css({"left":x,"top":y,"cursor":"move"});  
  121.                 }  
  122.             });  
  123.         }  
  124.     }  
  125. </script>  
这里使用的ajaxfileupload异步上传组件

html代码:

[html]  view plain copy
  1. <body>  
  2.         上传后的文件路径:  
  3.         <input type="text" class="url" />  
  4.         <span id="upload">上传</span>   
  5.         <span id="proview_img">预览</span>  
  6.         <br/>  
  7.           
  8.         <!-- 上传文件弹窗 -->  
  9.         <div id="upload_w">  
  10.             <!-- 遮盖部分 -->  
  11.             <div class="cover"></div>  
  12.             <div class="w_sub">  
  13.                 <form action="" method="post" enctype="multipart/form-data">  
  14.                     <table width="100%" cellpadding="0" cellspacing="0">  
  15.                         <tr><th class="title">图片上传<span class="close">×</span></th></tr>  
  16.                         <tr><td style="padding-left: 20px">选择图片文件:<br />  
  17.                             <input type="file"style="width: 95%; border: 1px solid #ddd; height: 25px; border-radius: 3px" name="file" id="file">  
  18.                             </td>  
  19.                         </tr>  
  20.                         <tr><td>${promptInfo }</td></tr>  
  21.                         <tr height="50px">  
  22.                             <td align="center"><input type="button" value="上传" class="sub_upload" /></td>  
  23.                         </tr>  
  24.                     </table>  
  25.                 </form>  
  26.             </div>  
  27.         </div>  
  28.           
  29.         <!-- 预览图片窗口 -->  
  30.         <div class="preview_w">  
  31.             <!-- 遮盖部分 -->  
  32.             <div class="cover"></div>  
  33.             <div class="preview">  
  34.                 <table width="100%" cellpadding="0" cellspacing="0">  
  35.                     <tr><th class="title">图片预览<span class="pre">×</span></th></tr>  
  36.                     <tr>  
  37.                         <td style="padding: 20px">  
  38.                             <img src="" id="image"/>  
  39.                         </td>  
  40.                     </tr>  
  41.                 </table>  
  42.             </div>  
  43.         </div>  
  44.     </body>  

css代码:

[html]  view plain copy
  1. <style type="text/css">  
  2. * {  
  3.     margin: 0px;  
  4.     padding: 0px;  
  5. }  
  6.   
  7. body {  
  8.     font: normal 15px/ 30px '微软雅黑'  
  9. }  
  10.   
  11. .url {  
  12.     width: 250px;  
  13.     height: 30px;  
  14.     border: 1px solid #CCCCCC;  
  15.     border-radius: 4px;  
  16. }  
  17.   
  18. span {  
  19.     color: #999999;  
  20.     cursor: pointer;  
  21. }  
  22.   
  23. span:hover {  
  24.     color: orange  
  25. }  
  26.   
  27. /*上传文件弹窗效果*/  
  28. #upload_w,.preview_w{display: none;}  
  29.   
  30. .cover {  
  31.     width: 100%;  
  32.     height: 100%;  
  33.     filter: alpha(opacity = 30);  
  34.     -moz-opacity: 0.3;  
  35.     -khtml-opacity: 0.3;  
  36.     opacity: 0.3;  
  37.     background: #CCCCCC;  
  38.     position: fixed;  
  39.     top: 0  
  40. }  
  41.   
  42. .w_sub {  
  43.     height: 150px;  
  44.     width: 350px;  
  45.     border: 3px solid #2CB9F2;  
  46.     background: #FFFFFF;  
  47.     position: fixed;  
  48.     padding: 10px;  
  49. }  
  50.   
  51. /*上传按钮*/  
  52. .sub_upload {  
  53.     height: 30px;  
  54.     width: 70px;  
  55.     background-color:#0A86CB;  
  56.     border-right:2px solid #0879B9;  
  57.     border-bottom:2px solid #0879B9;  
  58.     color:#FFFFFF;  
  59. }  
  60. .close,.pre{  
  61.     color:#2CB9F2;  
  62.     color:#0879B9;  
  63.     font-size: 25px;  
  64.     float: right;  
  65.     margin-right: 8px;  
  66.     line-height: 25px;  
  67.     cursor: pointer;  
  68. }  
  69. .preview{  
  70.     position: fixed;  
  71.     padding: 10px;  
  72.     border: 3px solid #2CB9F2;  
  73.     background:#FFFFFF;  
  74.     top:100px;  
  75.     left:100px;  
  76. }  
  77.   
  78. table{border:1px solid #2CB9F2}  
  79. .title{  
  80.      height:35px;  
  81.      background-color: #D6DEE3;  
  82.      font:normal 15px '微软雅黑';  
  83.      text-align: left;  
  84.      padding-left: 10px;  
  85.      color:#4C5A5F;  
  86. }  
  87. </style>  
需要引入js文件:

[html]  view plain copy
  1. <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>  
  2.         <script type="text/javascript" src="js/ajaxfileupload.js"></script>  

实现效果:

初始化界面:

上传窗口:

Java利用jQuery的ajaxFileUpload异步上传文件的几种方式_第1张图片

上传成功后将文件路径放入文本框中:

预览窗口:

Java利用jQuery的ajaxFileUpload异步上传文件的几种方式_第2张图片



3.springMVC + ajaxfileupload异步上传图片预览,裁剪并保存图片

1、整体效果图:

2、实现原理:

(1)利用input的onchange事件异步上传图片到服务器

(2)获取上传图片的相对地址,回显到img标签中

(3)利用jcrop裁剪图片,提交给后台裁剪的起始坐标,宽度、高度

(4)后台裁剪图片并保存


3、用到的插件:

(1)JCrop图片裁剪插件

(2)异步上传图片插件:Ajaxfileupload.js

4、实现:

(1)jsp关键代码:

[html]  view plain copy print ?
  1. <fieldset>  
  2.     <legend>头像上传</legend>  
  3.     <!-- 显示图片的img -->  
  4.     <img src="" id="realPic" width="400px" height="400px" />  
  5.     <!-- 缩略图预览 -->  
  6.     <div id="preview-pane">  
  7.         <div class="preview-container">  
  8.             <img src="" width="150px" height="150px" />  
  9.         </div>  
  10.     </div>  
  11.     <div class="container">  
  12.         <!-- 打开图片控制 -->  
  13.                 <span class="btn btn-success fileinput-button">   
  14.                     <i class="icon-plus icon-white"></i>   
  15.                     <span>选择图片</span>   
  16.                     <input type="file" onchange="ajaxFileUpload()" name="realPicFile" id="realPicFile" multiple />  
  17.                 </span>  
  18.                <!--       
  19.                这种做法IE不支持,拒绝访问.                                                          
  20.                <input id="realPicFile" value="选择图片" onchange="ajaxFileUpload()" type="file" style="display: none;" name="realPicFile" />  
  21.                <a class="btn btn-success" href="javascript:selectPic();" > <i class="icon-plus icon-white"></i>  
  22.                     选择图片   
  23.                </a>  
  24.                 -->  
  25.         <!-- 上传并裁剪图片 -->  
  26.         <img src="${ctx}/images/ajax-loader.gif" id="loading" style="display: none;">    
  27.         <a class="btn btn-success" href="javascript:cutPic();"><i class="icon-picture icon-white"></i>保存头像</a>  
  28.         <!-- 获取裁剪的起始坐标和宽度、高度给后台 -->  
  29.         <form id="coords" class="coords">  
  30.             <div class="inline-labels">  
  31.                 <input type="hidden" size="4" id="x1" name="x1" />  
  32.                 <input type="hidden" size="4" id="y1" name="y1" />  
  33.                 <input type="hidden" size="4" id="x2" name="x2" />  
  34.                 <input type="hidden" size="4" id="y2" name="y2" />  
  35.                 <input type="hidden" size="4" id="w" name="w" />  
  36.                 <input type="hidden" size="4" id="h" name="h" />  
  37.             </div>  
  38.          </form>  
  39.     </div>  
  40. </fieldset>  

控制样式的CSS :

[css]  view plain copy print ?
  1. .jcrop-holder #preview-pane {  
  2.   width:156px;  
  3.   height:156px;   
  4.   displayblock;  
  5.   positionabsolute;  
  6.   /*z-index: 2000;*/  
  7.   top: 0px;  
  8.   right: -200px;  
  9.   padding6px;  
  10.   border1px rgba(0,0,0,.4solid;  
  11.   background-colorwhite;  
  12.   
  13.   -webkit-border-radius: 6px;  
  14.   -moz-border-radius: 6px;  
  15.   border-radius: 6px;  
  16.   
  17.   -webkit-box-shadow: 1px 1px 5px 2px rgba(0000.2);  
  18.   -moz-box-shadow: 1px 1px 5px 2px rgba(0000.2);  
  19.   box-shadow: 1px 1px 5px 2px rgba(0000.2);  
  20. }  
  21.   
  22. /* The Javascript code will set the aspect ratio of the crop 
  23.    area based on the size of the thumbnail preview, 
  24.    specified here */  
  25. #preview-pane .preview-container {  
  26.   width156px;  
  27.   height156px;  
  28.   overflowhidden;  
  29. }  
  30. #target-pane {  
  31.     width400px;  
  32.     height400px;  
  33. }  
  34.   
  35.   
  36. .fileinput-button {  
  37.   positionrelative;  
  38.   overflowhidden;  
  39. }  
  40. .fileinput-button input {  
  41.   positionabsolute;  
  42.   top: 0;  
  43.   right: 0;  
  44.   margin0;  
  45.   opacity: 0;  
  46.   filter: alpha(opacity=0);  
  47.   transform: translate(-300px0) scale(4);  
  48.   font-size23px;  
  49.   directionltr;  
  50.   cursorpointer;  
  51. }  

注意fileinput-button这个样式,本人对css不熟悉,所以这个代码是从jquery-file-upload插件中拷贝过来的,大概的意思是将file的input放到按钮上,置为透明,这样就能够兼容IE,否则如果隐藏input,而触发它的click事件,IE认为这样做不安全,报拒绝访问的错误

(2)、javascript关键代码:

[javascript]  view plain copy print ?
  1. //Create variables (in this scope) to hold the API and image size  
  2. var jcrop_api, boundx, boundy, path;  
  3. /** 
  4.  * 更新缩略图,实现原理:根据原图框选的内容,显示到缩略图上,而缩略图也是原图是进行了放大,只是超过img范围的部分被隐藏 
  5.  */  
  6. function updatePreview(c) {  
  7.     if (parseInt(c.w) > 0) {  
  8.         $('#x1').val(c.x);  
  9.         $('#y1').val(c.y);  
  10.         $('#x2').val(c.x2);  
  11.         $('#y2').val(c.y2);  
  12.         $('#w').val(c.w);  
  13.         $('#h').val(c.h);  
  14.         
  15.         var rx = xsize / c.w;  
  16.         var ry = ysize / c.h;  
  17.   
  18.         // 精确计算图片的位置  
  19.         $pimg.css({  
  20.             width : Math.round(rx * boundx) + 'px',  
  21.             height : Math.round(ry * boundy) + 'px',  
  22.             marginLeft : '-' + Math.round(rx * c.x) + 'px',  
  23.             marginTop : '-' + Math.round(ry * c.y) + 'px'  
  24.         });  
  25.     }  
  26. }  
  27.   
  28. /** 
  29.  * 异步上传图片 
  30.  * @returns {Boolean} 
  31.  */  
  32. function ajaxFileUpload() {  
  33.     $("#loading").ajaxStart(function() {  
  34.         $(this).show();  
  35.     })//开始上传文件时显示一个图片    
  36.     .ajaxComplete(function() {  
  37.         $(this).hide();  
  38.     });//文件上传完成将图片隐藏起来    
  39.   
  40.     var file = $("#realPicFile").val();  
  41.     if(!/\.(gif|jpg|jpeg|png|JPG|PNG)$/.test(file))  
  42.     {  
  43.         Error("不支持的图片格式.图片类型必须是.jpeg,jpg,png,gif格式.");  
  44.         return false;  
  45.     }  
  46.       
  47.     $.ajaxFileUpload({  
  48.         url : Util.getContentPath() + '/user/uploadHeaderPicTmp.do?inputId=realPicFile',//用于文件上传的服务器端请求地址    
  49.         secureuri : false,//一般设置为false    
  50.         fileElementId : 'realPicFile',//文件上传空间的id属性  <input type="file" id="file" name="file" />    
  51.         dataType : 'json',//返回值类型 一般设置为json    
  52.         success : function(data, status) //服务器成功响应处理函数    
  53.         {     
  54.             // 图片在服务器上的相对地址,加随机数防止不刷新  
  55.             path = Util.getContentPath() + data.path + "?" + Math.random();  
  56.             $("#realPic").attr("src", path);  
  57.             var imgs = $(".jcrop-holder").find("img");  
  58.             // 原本有图片,重新上传后,所有的img都需要刷新  
  59.             imgs.each(function (i, v) {  
  60.                 $(this).attr("src", path);  
  61.             });  
  62.             $('#preview-pane .preview-container img').attr("src", path);  
  63.               
  64.             // 切图样式  
  65.             // Grab some information about the preview pane  
  66.             $preview = $('#preview-pane'), $pcnt = $('#preview-pane .preview-container'), $pimg = $('#preview-pane .preview-container img'),  
  67.             xsize = $pcnt.width(), ysize = $pcnt.height();  
  68.             //console.log('init', [ xsize, ysize ]);  
  69.               
  70.             $('#realPic').Jcrop({  
  71.                 onChange : updatePreview, //切图框改变事件  
  72.                 onSelect : updatePreview, // 切图框选择事件  
  73.                 onRelease: clearCoords, // 切图框释放的事件  
  74.                 bgFade   : true,  
  75.                 bgOpacity: .8, // 截图框以外部分的透明度  
  76.                 setSelect: [10, 10, 100, 100], // 默认选择的区域  
  77.             aspectRatio : 1 //xsize / ysize 截图比例,这里我采用1 : 1 的比例,即切出来的为正方形  
  78.             }, function() {  
  79.                 // Use the API to get the real image size  
  80.                 var bounds = this.getBounds();  
  81.                 boundx = bounds[0];  
  82.                 boundy = bounds[1];  
  83.                 // Store the API in the jcrop_api variable  
  84.                 jcrop_api = this;  
  85.                 // Move the preview into the jcrop container for css positioning  
  86.                 $preview.appendTo(jcrop_api.ui.holder);  
  87.             });  
  88.         },  
  89.         error : function(data, status, e)//服务器响应失败处理函数    
  90.         {  
  91.             Error(e);  
  92.         }  
  93.     });  
  94.     return false;  
  95. }  
  96.   
  97. function _getShowWidth(str) {  
  98.     return _getValue(str, "width");  
  99. }  
  100.   
  101. function _getShowHeight(str) {  
  102.     return _getValue(str, "height");  
  103. }  
  104.   
  105. function _getValue (str, key) {  
  106.     var str = str.replace(/\:|\;|\s/g, '').toLowerCase();  
  107.     var pos = str.indexOf(key);  
  108.     if (pos >= 0) {  
  109.         // 截取  
  110.         var tmp = str.substring(pos, str.length);  
  111.         var px = tmp.indexOf("px");  
  112.         if (px > 0){  
  113.             var width = tmp.substring(key.length, px);  
  114.             return width;  
  115.         }  
  116.         return 0;  
  117.     }  
  118.     return 0;  
  119. }  
  120.   
  121. /** 
  122.  * 裁剪图片 
  123.  */  
  124. function cutPic() {  
  125.     // 初始化数据  
  126.     var x1 = $('#x1').val() == "" ? 0 : $('#x1').val();  
  127.     var y1 = $('#y1').val() == "" ? 0 : $('#y1').val();  
  128.     var x2 = $('#x2').val();  
  129.     var y2 = $('#y2').val();  
  130.     var w = $('#w').val() == "" ? 150 : $('#w').val();  
  131.     var h= $('#h').val() == "" ? 150 : $('#h').val();  
  132.       
  133.     var srcFile = $("#realPic").attr("src");  
  134.     if (srcFile == "" || !srcFile) {  
  135.         Error("没有选择任何图片.");  
  136.         return;  
  137.     }  
  138.        
  139.     var showDiv = $(".jcrop-holder > .jcrop-tracker");  
  140.     // 从压缩存放图片的div中获取压缩后显示的宽度和高度,用来交给后台同比例进行裁剪  
  141.     // width: 404px; height: 304px; position: absolute; top: -2px; left: -2px; z-index: 290; cursor: crosshair;  
  142.     var style = showDiv.attr("style");  
  143.     // 原图片页面显示的宽度  
  144.     var showWidth = _getShowWidth(style);  
  145.     // 原图片页面显示的高度  
  146.     var showHeight = _getShowHeight(style);  
  147.     // console.log(showWidth + " " + showHeight);  
  148.     // 原地图的src地址,去掉后边防止不刷新的随机数  
  149.     srcFile = srcFile.substring(0, srcFile.indexOf("?"));  
  150.     $.ajax({  
  151.         type : "post",  
  152.         dataType : "json",  
  153.         url : Util.getContentPath() + "/user/uploadHeaderPic.do",  
  154.         data : {  
  155.             srcImageFile : srcFile,  
  156.             x : x1,  
  157.             y : y1,  
  158.             destWidth : w,  
  159.             destHeight : h,  
  160.             srcShowWidth : showWidth,  
  161.             srcShowHeight : showHeight,  
  162.         },  
  163.         success : function(data) {  
  164.             var okCallBack = function () {  
  165.                 this.top.window.location = Util.getContentPath() + "/user/pcModiInfoInit.do";  
  166.             };  
  167.             var msg = eval(data);  
  168.             if(msg && msg.msg)  
  169.                 if (msg.code == 1)  
  170.                     Alert(msg.msg, okCallBack);  
  171.                 else Error(msg.msg, okCallBack);  
  172.             else {  
  173.                 Error("上传失败,请稍后重试.", okCallBack);  
  174.                 return;  
  175.             }  
  176.         },  
  177.         error : function () {  
  178.             Error ("上传失败,请稍后重试.") ;  
  179.         }  
  180.     });  
  181. }  
  182.   
  183. function clearCoords()  
  184. {  
  185.   $('#coords input').val('');  
  186. };  

(3)springMVC代码:

[java]  view plain copy print ?
  1. @RequestMapping("uploadHeaderPicTmp")  
  2.     @ResponseBody  
  3.     public String uploadHeaderPic(String inputId, MultipartHttpServletRequest request) {  
  4.         try {  
  5.             MultipartFile realPicFile = request.getFile(inputId);  
  6.             InputStream in = realPicFile.getInputStream();  
  7.             String path = request.getSession().getServletContext().getRealPath("/");  
  8.             path += TMP;  
  9.             User loginUser = SystemUtil.getLoginUser(request.getSession());  
  10.             String fileName = loginUser.getName() + "." + FilenameUtils.getExtension(realPicFile.getOriginalFilename());  
  11.             File f = new File(path + "/" + fileName);  
  12.             FileUtils.copyInputStreamToFile(in, f);  
  13.             return "{\"path\" : \"" + TMP + "/" + fileName + "\"}";  
  14.         } catch (Exception e) {  
  15.             LOG.error("upload header picture error : ", e);  
  16.         }  
  17.         return null;  
  18.     }  
  19.   
  20.     @RequestMapping("uploadHeaderPic")  
  21.     @ResponseBody  
  22.     public GeneralMessage cutImage(String srcImageFile, int x, int y, int destWidth, int destHeight, int srcShowWidth, int srcShowHeight,  
  23.             HttpServletRequest request) {  
  24.         try {  
  25.             String path = request.getSession().getServletContext().getRealPath("/");  
  26.             Image img;  
  27.             ImageFilter cropFilter;  
  28.             String srcFileName = FilenameUtils.getName(srcImageFile);  
  29.             // 读取源图像    
  30.             File srcFile = new File(path + TMP + "/" + srcFileName);  
  31.   
  32.             BufferedImage bi = ImageIO.read(srcFile);  
  33.             //前端页面显示的并非原图大小,而是经过了一定的压缩,所以不能使用原图的宽高来进行裁剪,需要使用前端显示的图片宽高  
  34.             int srcWidth = bi.getWidth(); // 源图宽度    
  35.             int srcHeight = bi.getHeight(); // 源图高度  
  36.             if (srcShowWidth == 0)  
  37.                 srcShowWidth = srcWidth;  
  38.             if (srcShowHeight == 0)  
  39.                 srcShowHeight = srcHeight;  
  40.   
  41.             if (srcShowWidth >= destWidth && srcShowHeight >= destHeight) {  
  42.                 Image image = bi.getScaledInstance(srcShowWidth, srcShowHeight, Image.SCALE_DEFAULT);//获取缩放后的图片大小    
  43.                 cropFilter = new CropImageFilter(x, y, destWidth, destHeight);  
  44.                 img = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), cropFilter));  
  45.                 BufferedImage tag = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);  
  46.                 Graphics g = tag.getGraphics();  
  47.                 g.drawImage(img, 00null); // 绘制截取后的图    
  48.                 g.dispose();  
  49.   
  50.                 String ext = FilenameUtils.getExtension(srcImageFile);  
  51.   
  52.                 path += HEADER_PIC;  
  53.                 User loginUser = SystemUtil.getLoginUser(request.getSession());  
  54.                 String fileName = loginUser.getName() + "." + ext;  
  55.                 File destImageFile = new File(path + "/" + fileName);  
  56.                 // 输出为文件    
  57.                 ImageIO.write(tag, ext, destImageFile);  
  58.   
  59.                 loginUser.setPicPath(SystemConst.SYSTEM_CONTEXT_PATH_VALUE + HEADER_PIC + "/" + fileName);  
  60.                 userService.update(loginUser);  
  61.                 // 删除原临时文件  
  62.                 srcFile.delete();  
  63.   
  64.                 GeneralMessage msg = new GeneralMessage();  
  65.                 msg.setCode(GeneralMessage.SUCCESS);  
  66.                 msg.setMsg("上传成功!");  
  67.                 return msg;  
  68.             }  
  69.         } catch (Exception e) {  
  70.             e.printStackTrace();  
  71.         }  
  72.         return null;  
  73.     }  


4.Android+struts2实现文件图片上传,附源码(侧重服务端开发)


前言

项目中遇到Android手机聊天的图片、语音文件保存到服务器,网上搜索一下大概3种思路:

1.servlet实现,有很多文章,利用DiskFileUpload

2.使用smartupload未学习

3.利用strtus2自带的文件上传功能。

由于strtus2已广泛应用与企业应用,且上手较快,学习成本低、配置简单。文件上传功能已封装,简单易用,故毫不犹豫选择他。

网上这方面的资料不少,但很多重复的,且比较乱,新手可能很难找到自己想要的。总算自己捣鼓半天完成了功能,整理做下笔记,供大家参考。最后附上源码

 

Android客户端

[java]  view plain copy print ?
  1. //要用到三个东东来做Post:HttpClient,httpPost,MultipartEntity  
  2. HttpClient httpClient = new DefaultHttpClient();   
  3.   
  4.         httpClient.getParams().setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1 );  
  5.   
  6.         HttpPost httpPost = new HttpPost( "http://localhost:8680/upload/chat/uploadFile" );  
  7.   
  8.         MultipartEntity postEntity = new MultipartEntity();  
  9.   
  10.         // 字符用StringBody  
  11.         String fileName = "2.jpg";  
  12.   
  13.         ContentBody cbFileName;  
  14.           
  15.         cbFileName = new StringBody( fileName );  
  16.   
  17.         // 文件用FileBody,并指定文件类型  
  18.               
  19.         File file = new File( "D:\\FTP\\2.jpg");  
  20.         ContentBody cbFileData = new FileBody( file, "image/jpg" );  
  21.   
  22.   
  23.         // 把上面创建的这些Body全部加到Entity里面去。  
  24.         // 注意他们的key,这些key在Struts2服务器端Action的代码里必须保持一致!!  
  25.         postEntity.addPart( "fileName", cbFileName );  
  26.         postEntity.addPart( "fileData", cbFileData );  
  27.   
  28.         httpPost.setEntity( postEntity );  
  29.         // 下面这句话就把数据提交到服务器去了  
  30.         HttpResponse response = httpClient.execute( httpPost );  

 

服务端struts2

配置web.xml、引入相应jar包、等本文不展开论述,

struts.xml配置

[html]  view plain copy print ?
  1. <package name="chat" namespace="/chat" extends="struts-default">  
  2.         <action name="uploadFile" class="com.tch.action.FileUploadAction" method="upload">  
  3.         </action>  
  4.     </package>  

贴上Action类

[java]  view plain copy print ?
  1. // 注意这些变量名,看见了没? 和Struts2的FormBean是一样的。  
  2.     // 要和客户端添加字段时的关键字保持一致!!  
  3.     private String fileName = null;  
  4.     private String fileData = null;  
  5.     //针对每个字段的关键字,下面的这些Set方法必须一个不少,否则你什么也得不到  
  6.     public void setFileName(String fileName) {  
  7.         this.fileName = fileName;  
  8.     }  
  9.     public void setFileData(String fileData) {  
  10.         this.fileData = fileData;  
  11.     }  
[java]  view plain copy print ?
  1. public String upload()  
  2.     {  
  3.         String webappPath = findServerPath();  
  4.           
  5.         //path=D:\apache-tomcat-6.0.36\webapps\dqapi\  
  6.         //String path = ServletActionContext.getServletContext().getRealPath("/");  
  7.         //appPath=/dqapi  
  8.         //String appPath = ServletActionContext.getServletContext().getContextPath();  
  9.         String chatFile_path = ServletActionContext.getServletContext().getInitParameter("UPLOAD_CHAT_FILE_PATH");  
  10.         FileCopyUtil util = new FileCopyUtil();  
  11.         String[] array = fileName.split("\\.");  
  12.         String fileType = array[array.length-1];  
  13.           
  14.         //String destDir = path.replace(appPath, chatFile_path);  
  15.         String destDir = webappPath + chatFile_path;  
  16.         //先获取HttpServletResponse  
  17.         HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get( ServletActionContext.HTTP_RESPONSE );  
  18.   
  19.         //打开数据流,把要给客户端返回的数据写进数据流  
  20.         OutputStream writer = null;  
  21.   
  22.         ......  
  23.           
  24.         // 这里不用再返回其他字符串了。  
  25.         // 客户端接收的不是这里返回的数据,这个是显示结果网页才会用到的返回值。  
  26.   
  27.         return null;  
  28.   
  29.     }  


 

 

 将用户上传文件与web项目本身分离

项目路径D:\apache-tomcat-6.0.36\webapps\upload

Java利用jQuery的ajaxFileUpload异步上传文件的几种方式_第3张图片

保存上传的文件到webapps目录下指定位置
 Java利用jQuery的ajaxFileUpload异步上传文件的几种方式_第4张图片

文件拷贝代码如下

[java]  view plain copy print ?
  1. public String copyFile(String fileType,String fileData,String destDir) throws IOException  
  2.     {  
  3.         Date date = new Date();  
  4.         String dirName = new SimpleDateFormat("yyyyMMdd").format(date);  
  5.         String newFileName = new SimpleDateFormat("yyyyMMddHHmmss_SSS").format(date);&nbs

你可能感兴趣的:(异步上传文件)