ajaxFileUpload是一款基于jQuery的ajax上传方式的文件上传插件,它没有对上传控件作美化(使用原生态的上传控件),只是提供了异步上传的功能,但用它来作异步上传确实很简单和方便。下来我来说说使用步骤:
一:引入JS文件——ajaxFileUpload.js,引入之前需先引入jquery文件。由于ajaxFileUpload用的jquery版本比较低,此插件现在已经不更新了,为了能正常使用此插件,需要在ajaxFileUpload.js里加入handleError函数(此函数jquery1.4.2才有,之后的版本就废除了),此函数代码如下(我的资源中提供了此插件的文件):
二:用它的上传函数ajaxFileUpload来上传:
- handleError: function( s, xhr, status, e ) {
- // If a local callback was specified, fire it
- if ( s.error ) {
- s.error.call( s.context || s, xhr, status, e );
- }
- // Fire the global callback
- if ( s.global ) {
- (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
- }
- },
参数说明:
1、url 服务器上传接口地址,这个就不用说了吧。 2,fileElementId 文件控件的id:<input type="file" id="file" name="file" />(文件控件的id和name属性都写上,避免浏览器兼容问题)。 3,secureuri 是否启用安全提交,默认为false。 4,dataType 服务器返回的数据类型。可以为xml,script,json,html。 5,success 成功回调函数(回调函数得不到返回信息为JSON方式的数据,真是个坑)。 6,error 失败回调函数。 7,data 自定义参数(file对象不用再写在这里,只要把除file对象之外的参数写进去)。 8, type 传参方式(post和get),最好用post。
实例:
- var serverPath = serverAddress;
- var user = JSON.parse(sessionStorage.getItem("user"));
- var addr_uploadPhoto = serverPath + '/api/user/uploadUserImage.shtml';
- function uploadPhoto(){
- $.ajaxFileUpload( {
- url : addr_uploadPhoto,
- secureuri : false,
- fileElementId : 'file',
- dataType : 'json',
- data:{userId:user.id},
- success : function(data)
- {
- alert("上传成功!");
- }
- })
- }
控件本身是不支持多文件上传的,为了实现多文件上传,我们要改源码(createUploadForm方法):
前提条件: ajaxFileUpload.js插件多文件上传 步骤: 1、修改源码,(源码只支持单个文件的上传): 复制代码 代码如下: //修改前代码------- //var oldElement = jQuery('#' + fileElementId); //var newElement = jQuery(oldElement).clone(); //jQuery(oldElement).attr('id', fileId); //jQuery(oldElement).before(newElement); //jQuery(oldElement).appendTo(form); //修改前代码------- //修改后代码------- for(var i in fileElementId){ var oldElement = jQuery('#' + fileElementId[i]); var newElement = jQuery(oldElement).clone(); jQuery(oldElement).attr('id', fileId); jQuery(oldElement).before(newElement); jQuery(oldElement).appendTo(form); } //修改后代码------- 2、使用方法: 复制代码 代码如下: $.ajaxFileUpload({ url : "./upload/upload.action", secureuri : false, //fileElementId:'uploadfile1',//原使用方法 fileElementId : ['uploadfile1','uploadfile2','uploadfile3','uploadfile4','uploadfile5'],//现使用方法 dataType : 'json', success : function(data) { ajaxLoadEnd(); if (data.result == "success") { $.messager.alert('信息','导入成功。','info'); } else { $('#import_right').dialog('open'); $.messager.alert('信息','导入失败。<br>错误信息:'+data.message,'error'); } }, error : function(data, status, e) { ajaxLoadEnd(); $.messager.alert('信息','导入失败。<br>错误信息:网络异常或表单数据错误。','error'); } });
jquery ajaxFileUpload.js插件支持多文件上传的方法
最新推荐文章于 2024-03-15 09:35:00 发布