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
- <script type="text/javascript" src="<%=basePath%>/js/jquery/jquery-1.8.0.min.js"></script>
- <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 )
- createUploadIframe: function(id, uri)
- {
- //create frame
- var frameId = 'jUploadFrame' + id;
- if(window.ActiveXObject) {
- if(jQuery.browser.version=="9.0"||jQuery.browser.version=="10.0") {
- io = document.createElement('iframe');
- io.id = frameId;
- io.name = frameId;
- } else if(jQuery.browser.version=="6.0"||jQuery.browser.version=="7.0"||jQuery.browser.version=="8.0") {
- var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
- if(typeof uri== 'boolean'){
- io.src = 'javascript:false';
- }
- else if(typeof uri== 'string'){
- io.src = uri;
- }
- }
- }
2、form表单及上传控件
form表单设置为:
- enctype="multipart/form-data" id="addForm" method="post"
- <input id="upload" name="upload" size="50" type="file" />
- <a class="easyui-linkbutton" iconCls="icon-upload" onclick="ajaxFileUploadCheckType('/sys/file/uploadSysFile.action?fileVo.status=0')" >上传</a>
- <img src="<%=basePath%>/img/loading_16x16.gif" id="loading" style="display: none;">
- function ajaxFileUploadCheckType(url){
- var str="";
- var re=new RegExp("(.pdf|.PDF)$");
- var upload=$("#upload").val();
- if(upload=="")
- str+="请选择要上传的附件!<br/>";
- else if(!re.test(upload.toLowerCase()))
- str+="请上传PDF格式的文件!!";
- if(str=="")
- ajaxFileUpload(url);
- else
- alert(str);
- }
- //文件上传
- function ajaxFileUpload(url1)
- {
- $("#loading")
- .ajaxStart(function(){
- $(this).show();
- })//开始上传文件时显示一个等待图片
- .ajaxComplete(function(){
- $(this).hide();
- });//文件上传完成将图片隐藏起来
- var fileSelect=$("#fileSelect").val(); //是否选择了文件类型
- var url2=url1;
- if(fileSelect!=undefined&&fileSelect!=null&&fileSelect!=''){
- if(url1.indexOf('?')>0)
- url2=encodeURI(url1+"&fileVo.fileTypeId="+fileSelect);
- else
- url2=encodeURI(url1+"?fileVo.fileTypeId="+fileSelect);
- }
- var tableName=$("#tableName").val();
- if(url2.indexOf('?')>0)
- url2=encodeURI(url2+"&fileVo.tableName="+tableName);
- else
- url2=encodeURI(url2+"?fileVo.tableName="+tableName);
- var fid=$("#fid").val();
- if(url2.indexOf('?')>0)
- url2=encodeURI(url2+"&fileVo.fid="+fid);
- else
- url2=encodeURI(url2+"?fileVo.fid="+fid);
- $.ajaxFileUpload
- (
- {
- url:url2,//用于文件上传的服务器端请求地址
- secureuri:false,//一般设置为false
- fileElementId:'upload',//文件上传空间的id属性 <input type="file" id="upload" name="upload" />
- // type:'POST',
- dataType: 'text',//返回值类型 一般设置为json
- //contentType: "application/x-www-form-urlencoded; charset=utf-8",
- success: function (data, status) //服务器成功响应处理函数
- {
- //alert((data));
- var result=eval('('+data+')');
- generateFileList(result,"type"); //使用ajax方式重新长生附件列表
- },
- error: function (data, status, e)//服务器响应失败处理函数
- {
- $.messager.alert('错误提示',"文件上传出现异常,请重新上传或联系管理员!","error");
- }
- }
- )
- return false;
- }
3、Struts2的XML配置及服务器端处理
XML配置:
- <package name="sys.file" namespace="/sys/file" extends="globalpackage">
- lt;action name="uploadSysFile" class="com.cnpc.sys.action.FileUploadAction"
- method="uploadSysFile">
- lt;/action>
- ……
服务器端Action处理:
- package com.cnpc.sys.action;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.Date;
- import java.util.List;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import org.apache.struts2.ServletActionContext;
- import com.cnpc.framework.common.action.BaseAction;
- import com.cnpc.framework.common.exception.GlobalException;
- import com.cnpc.framework.common.servicefactory.SystemInstance;
- import com.cnpc.sys.entity.Dictionary;
- import com.cnpc.sys.entity.Employee;
- import com.cnpc.sys.service.IDictionaryService;
- import com.cnpc.sys.service.IEmployeeService;
- import com.cnpc.sys.service.ISysFileService;
- import com.cnpc.sys.vo.SysFileVo;
- import com.cnpc.utils.DateUtils;
- import com.cnpc.utils.PropertiesTools;
- import com.cnpc.utils.StrUtils;
- //附件上传处理类
- public class FileUploadAction extends BaseAction {
- private ISysFileService sysFileService = (ISysFileService) SystemInstance
- .getInstance().getBean(ISysFileService.class);
- private IDictionaryService dictionaryService = (IDictionaryService) SystemInstance
- .getInstance().getBean(IDictionaryService.class);
- private IEmployeeService employeeService = (IEmployeeService) SystemInstance
- .getInstance().getBean(IEmployeeService.class);
- private SysFileVo fileVo;
- private File upload;// 实际上传文件
- private String uploadContentType; // 文件的内容类型
- private String uploadFileName; // 上传文件名
- private List<SysFileVo> fileVoList;
- private String message = "你已成功上传文件";
- private String tableName;
- private String year;
- private List<SysFileVo> volist;
- public String getYear() {
- return year;
- }
- public void setYear(String year) {
- this.year = year;
- }
- public String getTableName() {
- return tableName;
- }
- public void setTableName(String tableName) {
- this.tableName = tableName;
- }
- public List<SysFileVo> getVolist() {
- return volist;
- }
- public void setVolist(List<SysFileVo> volist) {
- this.volist = volist;
- }
- public SysFileVo getFileVo() {
- return fileVo;
- }
- public void setFileVo(SysFileVo fileVo) {
- this.fileVo = fileVo;
- }
- public File getUpload() {
- return upload;
- }
- public void setUpload(File upload) {
- this.upload = upload;
- }
- public String getUploadContentType() {
- return uploadContentType;
- }
- public void setUploadContentType(String uploadContentType) {
- this.uploadContentType = uploadContentType;
- }
- public String getUploadFileName() {
- return uploadFileName;
- }
- public void setUploadFileName(String uploadFileName) {
- this.uploadFileName = uploadFileName;
- }
- public List<SysFileVo> getFileVoList() {
- return fileVoList;
- }
- public void setFileVoList(List<SysFileVo> fileVoList) {
- this.fileVoList = fileVoList;
- }
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
- public String uploadSysFile() throws GlobalException, IOException {
- String isAll=fileVo.getIsAll();
- Employee emp = employeeService.getEmployeeByID(getSessionContainer().getUserId());
- if (fileVo == null) {
- fileVo = new SysFileVo();
- }
- String[] str = saveUpload();
- fileVo.setFileName(str[0]);
- fileVo.setVirtualName(str[1]);
- fileVo.setFilePath(str[2].replace("\\", "\\\\"));
- if (fileVo != null) {
- if (fileVo.getEmpid() == null) {
- Integer empid = emp.getEmpid();
- fileVo.setEmpid(empid);
- }
- if (fileVo.getUploadTime() == null) {
- fileVo.setUploadTime(DateUtils.format(new Date(System
- .currentTimeMillis()), DateUtils.formatStr_yyyyMMdd));
- }
- if (fileVo.getTableName() == null) {
- fileVo.setTableName(tableName);
- }
- if(fileVo.getYear()==null){
- if(year==null)
- year=DateUtils.getYear();
- fileVo.setYear(year);
- }
- if(fileVo.getIid()==null){
- fileVo.setIid(emp.getInstitute().getIid());
- }
- fileVo = sysFileService.addSysFileVo(fileVo);
- }
- if (fileVoList == null) {
- fileVoList = new ArrayList<SysFileVo>();
- }
- fileVo.setIsAll(isAll);
- if(fileVo.getIsAll()!=null&&fileVo.getIsAll().equals("1")){
- fileVoList = sysFileService.getAllSysFileByInfoId(
- fileVo.getTableName(), fileVo.getFid());
- }else{
- fileVoList = sysFileService.getSysFileByInfoId(
- fileVo.getTableName(),null, fileVo.getFid(),fileVo.getStatus());
- }
- String jsonStr = getJsonForFileList(fileVoList);
- HttpServletResponse response = getCurrentResponse();
- HttpServletRequest request=getCurrentRequest();
- request.setCharacterEncoding(ENCODING);
- response.setCharacterEncoding(ENCODING);
- response.setContentType("text/html");
- outPutString(jsonStr);
- return NONE;
- }
- public String getJsonForFileList(List<SysFileVo> filelist) {
- if (filelist == null)
- return "[]";
- StringBuffer buffer = new StringBuffer("[");
- for (SysFileVo vo : filelist) {
- buffer.append("{'id':'" + vo.getFileId() + "' ,'name':'"
- + vo.getFileName() + "','path':'"
- + vo.getFilePath().replace("\\", "\\\\") + "','typeName':'"
- + vo.getFileTypeName() + "','typeid':'"
- + vo.getFileTypeId() + "','status':'"
- + vo.getStatus() + "'},");
- }
- if (buffer.length() > 1)
- buffer = new StringBuffer(buffer.substring(0, buffer.length() - 1));
- buffer.append("]");
- return buffer.toString();
- }
- @SuppressWarnings("deprecation")
- public String[] saveUpload() throws IOException {
- String[] result = new String[3];
- try {
- if (uploadFileName != null && !"".equals(uploadFileName)) {