jquery实现异步文件上传ajaxfileupload.js


Posted in jQuery onOctober 23, 2020

本文实例为大家分享了jquery实现异步文件上传的具体代码,供大家参考,具体内容如下

ajaxfileupload.js 异步上传文件:

直接引用。

调用方法:

$.ajaxFileUpload({ 
 url:'',//后台接口地址 
 type: "post", 
 secureuri: false, //一般设置为false 
 fileElementId: 'ofx', // 上传文件的id、name属性名 
 dataType: 'json', 
 success: function(data, status){ 
  
 }, 
 error: function(data, status, e){ 
 } 
 });

下面是ajaxfileupload.js,可直接复制并引用。

jQuery.extend({
 createUploadIframe: function(id, uri)
 {
  
 //create frame
 var frameId = 'jUploadFrame' + id;
 var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
 if(window.ActiveXObject)
 {
 if(typeof uri== 'boolean'){
 iframeHtml += ' src="' + 'javascript:false' + '"';

 }
 else if(typeof uri== 'string'){
 iframeHtml += ' src="' + uri + '"';

 } 
 }
 iframeHtml += ' />';
 jQuery(iframeHtml).appendTo(document.body);

 return jQuery('#' + frameId).get(0); 
 },
 createUploadForm: function(id,fileElementId,data,fileElement)
 {
 //create form 
 var formId = 'jUploadForm' + id;
 var fileId = 'jUploadFile' + id;
 var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>'); 
 if(data)
 {
 for(var i in data)
 {
 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
 } 
 }

 
 if(typeof(fileElementId) == 'string'){
 fileElementId = [fileElementId];
 }
 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);
 }
 
 
 
 //set attributes
 jQuery(form).css('position', 'absolute');
 jQuery(form).css('top', '-1200px');
 jQuery(form).css('left', '-1200px');
 jQuery(form).appendTo('body'); 
 return form;
 },

 ajaxFileUpload: function(s) {
  // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout 
  s = jQuery.extend({}, jQuery.ajaxSettings, s);
  var id = new Date().getTime()  
 var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data),s.fileElement);
 var io = jQuery.createUploadIframe(id, s.secureuri);
 var frameId = 'jUploadFrame' + id;
 var formId = 'jUploadForm' + id; 
  // Watch for a new set of requests
  if ( s.global && ! jQuery.active++ )
 {
 jQuery.event.trigger( "ajaxStart" );
 }   
  var requestDone = false;
  // Create the request object
  var xml = {} 
  if ( s.global )
   jQuery.event.trigger("ajaxSend", [xml, s]);
  // Wait for a response to come back
  var uploadCallback = function(isTimeout)
 { 
 var io = document.getElementById(frameId);
   try 
 { 
 if(io.contentWindow)
 {
  xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
     xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
  
 }else if(io.contentDocument)
 {
  xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
     xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
 }  
   }catch(e)
 {
 jQuery.handleError(s, xml, null, e);
 }
   if ( xml || isTimeout == "timeout") 
 { 
    requestDone = true;
    var status;
    try {
     status = isTimeout != "timeout" ? "success" : "error";
     // Make sure that the request was successful or notmodified
     if ( status != "error" )
  {
      // process the data (runs the xml through httpData regardless of callback)
      var data = jQuery.uploadHttpData( xml, s.dataType ); 
      // If a local callback was specified, fire it and pass it the data
      if ( s.success )
       s.success( data, status );
 
      // Fire the global callback
      if( s.global )
       jQuery.event.trigger( "ajaxSuccess", [xml, s] );
     } else
      jQuery.handleError(s, xml, status);
    } catch(e) 
 {
     status = "error";
     jQuery.handleError(s, xml, status, e);
    }

    // The request was completed
    if( s.global )
     jQuery.event.trigger( "ajaxComplete", [xml, s] );

    // Handle the global AJAX counter
    if ( s.global && ! --jQuery.active )
     jQuery.event.trigger( "ajaxStop" );

    // Process result
    if ( s.complete )
     s.complete(xml, status);

    jQuery(io).unbind()

    setTimeout(function()
   { try 
   {
   jQuery(io).remove();
   jQuery(form).remove(); 
   
   } catch(e) 
   {
   jQuery.handleError(s, xml, null, e);
   }   

   }, 100)

    xml = null

   }
  }
  // Timeout checker
  if ( s.timeout > 0 ) 
 {
   setTimeout(function(){
    // Check to see if the request is still happening
    if( !requestDone ) uploadCallback( "timeout" );
   }, s.timeout);
  }
  try 
 {

 var form = jQuery('#' + formId);
 jQuery(form).attr('action', s.url);
 jQuery(form).attr('method', 'POST');
 jQuery(form).attr('target', frameId);
   if(form.encoding)
 {
 jQuery(form).attr('encoding', 'multipart/form-data');   
   }
   else
 { 
 jQuery(form).attr('enctype', 'multipart/form-data'); 
   } 
   jQuery(form).submit();

  } catch(e) 
 { 
   jQuery.handleError(s, xml, null, e);
  }
 
 jQuery('#' + frameId).load(uploadCallback);
  return {abort: function(){
 try
 {
 jQuery('#' + frameId).remove();
 jQuery(form).remove();
 }
 catch(e){}
 }};
 },

 uploadHttpData: function( r, type ) {
  var data = !type;
  data = type == "xml" || data ? r.responseXML : r.responseText;
 
  // If the type is "script", eval it in global context
  if ( type == "script" )
   jQuery.globalEval( data );
  // Get the JavaScript object, if JSON is used.
  if ( type == "json" ){
 以下为新增代码///
   data = r.responseText;
   var start = data.indexOf(">");
   if(start != -1) {
  var end = data.indexOf("<", start + 1);
  if(end != -1) {
  data = data.substring(start + 1, end);
  }
 }
 }
   ///以上为新增代码///
   eval( "data = " + data );
  // evaluate scripts within html
  if ( type == "html" )
   jQuery("<div>").html(data).evalScripts();

  return data;
 },
 
 handleError: function( s, xml, status, e ) {
 // If a local callback was specified, fire it
 if ( s.error )
 s.error( xml, status, e );

 // Fire the global callback
 if ( s.global )
 jQuery.event.trigger( "ajaxError", [xml, s, e] );
 }
});

更多精彩内容,请点击《jQuery上传操作汇总》,《ajax上传技术汇总》进行深入学习和研究。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

jQuery 相关文章推荐
使用jQuery监听扫码枪输入并禁止手动输入的实现方法(推荐)
Mar 21 jQuery
jQuery EasyUI tree增加搜索功能的实现方法
Apr 27 jQuery
jQuery使用ajax_动力节点Java学院整理
Jul 05 jQuery
jQuery访问浏览器本地存储cookie、localStorage和sessionStorage的基本用法
Oct 20 jQuery
基于jquery.page.js实现分页效果
Jan 01 jQuery
如何用input标签和jquery实现多图片的上传和回显功能
May 16 jQuery
JQuery常用简单动画操作方法回顾与总结
Dec 07 jQuery
jQuery实现聊天对话框
Feb 08 jQuery
jQuery实现雪花飘落效果
Aug 02 jQuery
jQuery实现图片切换效果
Oct 19 jQuery
jQuery冲突问题解决方法
Jan 19 jQuery
jquery插件实现代码雨特效
Apr 24 jQuery
jquery实现抽奖功能
Oct 22 #jQuery
jQuery实现可以计算进制转换的计算器
Oct 19 #jQuery
jQuery实现计算器功能
Oct 19 #jQuery
jQuery实现推拉门效果
Oct 19 #jQuery
jQuery实现图片切换效果
Oct 19 #jQuery
jQuery实现回到顶部效果
Oct 19 #jQuery
jQuery实现放大镜案例
Oct 19 #jQuery
You might like
php读取excel文件示例分享(更新修改excel)
2014/02/27 PHP
[IE&amp;FireFox兼容]JS对select操作
2007/01/07 Javascript
点图片上一页下一页翻页效果
2008/07/09 Javascript
node.js中的fs.lstatSync方法使用说明
2014/12/16 Javascript
jQuery中filter()方法用法实例
2015/01/06 Javascript
jquery实现平滑的二级下拉菜单效果
2015/08/26 Javascript
快速学习jQuery插件 Form表单插件使用方法
2015/12/01 Javascript
详解Angular.js的$q.defer()服务异步处理
2016/11/06 Javascript
基于js实现的限制文本框只可以输入数字
2016/12/05 Javascript
使用vue-router beforEach实现判断用户登录跳转路由筛选功能
2018/06/25 Javascript
vue.js input框之间赋值方法
2018/08/24 Javascript
微信小程序全局变量的设置、使用、修改过程解析
2019/09/24 Javascript
使用Vue实现简单计算器
2020/02/25 Javascript
微信小程序实现自定义底部导航
2020/11/18 Javascript
[13:21]DOTA2国际邀请赛采访专栏:RSnake战队国士无双,Fnatic.Fly
2013/08/06 DOTA
pygame加载中文名mp3文件出现error
2017/03/31 Python
动态规划之矩阵连乘问题Python实现方法
2017/11/27 Python
python中不能连接超时的问题及解决方法
2018/06/10 Python
python入门:这篇文章带你直接学会python
2018/09/14 Python
pandas实现to_sql将DataFrame保存到数据库中
2019/07/03 Python
利用python实现逐步回归
2020/02/24 Python
python正则表达式实例代码
2020/03/03 Python
python正则表达式 匹配反斜杠的操作方法
2020/08/07 Python
python爬取股票最新数据并用excel绘制树状图的示例
2021/03/01 Python
英国著名音像制品和图书游戏购物网站:Zavvi
2016/08/04 全球购物
创业计划书的主要内容有哪些
2014/01/29 职场文书
医科大学毕业生自荐信
2014/02/03 职场文书
护理专业自荐信范文
2014/02/26 职场文书
爱的奉献演讲稿
2014/09/10 职场文书
2014年人力资源部工作总结
2014/11/19 职场文书
爱的承诺书
2015/01/20 职场文书
公司酒会主持词
2015/07/02 职场文书
安全温馨提示语大全
2015/07/14 职场文书
2015年政治教研组工作总结
2015/07/22 职场文书
初中毕业感言300字
2015/07/31 职场文书
2019最新版股权转让及委托持股协议书范本
2019/08/07 职场文书