/*
131108-xxj-ajaxFileUpload.js 无刷新上传图片 jquery 插件,支持 ie6-ie10
依赖:jquery-1.6.1.min.js
主方法:ajaxFileUpload 接受 json 对象参数
参数说明:
fileElementId:必选,上传文件域ID
url:必选,发送请求的URL字符串
fileFilter:可选,限定上传文件的格式(.jpg,.bmp,.gif,.png)
fileSize:可选,0 为无限制(IE浏览器不兼容)
data:可选,将和文件域一同post的参数(json对象)
其它:$.ajax 的参数均为可选参数
注:如遇到‘无法访问’的脚本错误提示则需要在响应流中加一段脚块一同输出:<script ...>document.domain = 'xxx.com';</script>
*/
jQuery.extend({
//创建 iframe 元素,接受提交及响应
createUploadIframe: function(id, uri) {
//create frame
var frameId = 'jUploadFrame' + id; if (window.ActiveXObject) {
//fix ie9 and ie 10-------------
if (jQuery.browser.version == "9.0" || jQuery.browser.version == "10.0") {
var 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;
}
}
} else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px'; document.body.appendChild(io); return io;
},
//创建 from 元素,用于提交的表单
createUploadForm: function(id, fileElementId, postData) {
//create form<span style="white-space:pre"> </span>
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone(); $(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//添加自定义参数
if (postData) {
//递归遍历JSON所有键值 function recurJson(json) {
for (var i in json) {
//alert(i+"="+json[i])
$("<input name='" + i + "' id='" + i + "' value='" + json[i] + "' />").appendTo(form);
if (typeof json[i] == "object") {
recurJson(json[i]);
}
}
} recurJson(postData);
}
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
},
//上传文件
//s 参数:json对象
ajaxFileUpload: function(s) {
s = jQuery.extend({fileFilter:"",fileSize:0}, jQuery.ajaxSettings, s);
//文件筛选
var fielName = $('#' + s.fileElementId).val();
var extention = fielName.substring(fielName.lastIndexOf(".") + 1).toLowerCase();
if (s.fileFilter && s.fileFilter.indexOf(extention) < 0) {
alert("仅支持 (" + s.fileFilter + ") 为后缀名的文件!");
return;
}
//文件大小限制
if (s.fileSize > 0) {
var fs = 0;
try {
if (window.ActiveXObject) {
//IE浏览器
var image = new Image();
image.dynsrc = fielName;
fs = image.fileSize;
} else {
fs = $('#' + s.fileElementId)[0].files[0].size;
}
} catch(e) {
}
if (fs > s.fileSize) {
alert("当前文件大小 (" + fs + ") 超过允许的限制值 (" + s.fileSize +")!");
return;
}
}
var id = new Date().getTime();
//创建 form 表单元素
var form = jQuery.createUploadForm(id, s.fileElementId, s.data);
//创建 iframe 贞元素
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
//监测是否有新的请求
if (s.global && !jQuery.active++) {
jQuery.event.trigger("ajaxStart"); //触发 AJAX 请求开始时执行函数。Ajax 事件。
}
var requestDone = false;
//创建请求对象
var xml = {};
if (s.global)
jQuery.event.trigger("ajaxSend", [xml, s]); //触发 AJAX 请求发送前事件
//上载完成的回调函数
var uploadCallback = function(isTimeout) {
var io = document.getElementById(frameId);
try {
//存在跨域脚本访问问题,如遇到‘无法访问’提示则需要在响应流中加一段脚块:<script ...>document.domain = 'xxx.com';</script>
if (io.contentWindow) { //兼容各个浏览器,可取得子窗口的 window 对象
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) { //contentDocument Firefox 支持,> ie8 的ie支持。可取得子窗口的 document 对象。
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.handleErrorExt(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") {
//处理数据(运行XML通过httpData不管回调)
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.handleErrorExt(s, xml, status);
} catch(e) {
status = "error";
jQuery.handleErrorExt(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 {
$(io).remove();
$(form).remove();
} catch(e) {
jQuery.handleErrorExt(s, xml, null, e);
} }, 100); xml = null; }
};
//超时检查,s.timeout 毫秒后调用 uploadCallback 回调函数提示请求超时
if (s.timeout > 0) {
setTimeout(function() {
// Check to see if the request is still happening
if (!requestDone) uploadCallback("timeout");
}, s.timeout);
}
try {
//设置动态 form 表单的提交参数
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if (form.encoding) {
form.encoding = 'multipart/form-data';
} else {
form.enctype = 'multipart/form-data';
}
$(form).submit(); } catch(e) {
jQuery.handleErrorExt(s, xml, null, e);
}
//向动态表单的页面加载事件中注册回调函数
if (window.attachEvent) {
document.getElementById(frameId).attachEvent('onload', uploadCallback);
} else {
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
return {
abort: function() {
}
}; },
//上传文件
uploadHttpData: function(r, type) {
//alert("type=" + type + ";uploadHttpData" + JSON.stringify(r))
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")
eval("data = " + data);
// evaluate scripts within html
if (type == "html")
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
},
handleErrorExt: 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]);
}
}
});
  function uploadImg(imgfileId, imgcontainerId) {
$.ajaxFileUpload({
fileElementId: imgfileId,
url: '/UploadImage',
dataType: 'json',
data: { id: 'aaa', name: 'bbb' },
beforeSend: function (XMLHttpRequest) {
//("loading");
},
success: function (data, textStatus) {
var img = "<img src='' width='300' height='300' />";
$("#" + imgcontainerId).append(img);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
var img = "图片上传失败!";
$("#" + imgcontainerId).append(img);
var msg = "服务器出错,错误内容:" + XMLHttpRequest.responseText;
$.messager.showWin({ msg: msg, title: '错误提示', color: 'red' });
},
complete: function (XMLHttpRequest, textStatus) {
//("loaded");
}
});
}

ajaxFileUpload.js 无刷新上传图片,支持多个参数同时上传,支持 ie6-ie10的更多相关文章

  1. js无刷新上传图片,服务端有生成缩略图,剪切图片,iphone图片旋转判断功能

    html: <form action="<{:AppLink('circle/uploadimg')}>" id="imageform" me ...

  2. 采用formdata做跨域的、无刷新、带进度条的文件上传

    以前做无刷新上传,都要用iframe,如果想有进度条,就千难万难,不得不用flash等插件来实现. 现在HTML5终于普及了,筒子们不用再那么痛苦了. 所有这一切都变得异常简单!! 不信?且看如下代码 ...

  3. TP3.2:实现Ajax无刷新上传图片

    1.基于TP3.2+ajaxfileupload进行无刷新上传图片,本次只上传一张,多张以后搞出来再发 2.效果:   3.html代码: <html> <head> < ...

  4. 无刷新上传图片,ajax 和 iframe

    iframe 上传 upload.html 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 ...

  5. nodejs利用ajax实现网页无刷新上传图片

    nodejs利用ajax实现网页无刷新上传图片 标签(空格分隔): nodejs 通常情况下上传图片是要通过提交form表单来实现的,但是这又不可避免的产生了网页转. 利用ajax技术和FormDat ...

  6. php无刷新上传图片和文件

    核心思想:通过Html的iframe标签属性操作顶级窗口,再用php动态无刷新上传图片文件. 示例如下: demo |------uploads #存放上传的文件 |------index.php | ...

  7. 使用SWFUpload无刷新上传图片

    使用SWFUpload组件无刷新上传图片 在做项目时,需要用到一个图片的无刷新上传,之前听说过SWFUpload,于是想要通过SWFUpload来进行图片的无刷新上传,由于我的项目属于是ASP.NET ...

  8. Thinkphp框架 -- ajax无刷新上传图片

    用Thinkphp框架做无刷新上传图片 视图层 View <!doctype html> <html lang="en"> <head> < ...

  9. js 无刷新文件上传 (兼容IE9 )

    之前项目中有个文件上传了需求,于是直接就使用了FormData对象异步上传,但是在测试得时候发现ie9无法正常上传(项目要求兼容IE9+),无奈,查资料得知IE9- 版本不支持formdata对象得异 ...

随机推荐

  1. STM32/GD32芯片信息(转)

    源:STM32/GD32芯片信息 因为需要自动适配芯片进行系统配置,所以我们有必要通过读取一些系统寄存器来获取必要信息.我们的代码需要兼容STM32F1/GD32F1/STM32F0/STM32F4 ...

  2. [cocos2d-x] --- CCNode类详解

    Email : awodefeng@163.com 1 CCNode是cocos2d-x中一个很重要的类,CCNode是场景.层.菜单.精灵等的父类.而我们在使用cocos2d-x时,接触最多的就是场 ...

  3. jenkins 构建时,取消构建测试类

    如图 点击配置,添加clean install  -Dmaven.test.skip=true 保存即可

  4. sublime text2的插件熟悉

    今天加班,开会.于是整理下sublime text的插件. 1.安装了tag插件.负责html的格式化.从百度云下载了文件,放入了插件包的目录下. 2.启用了alignment 快捷键 ctr+alt ...

  5. Scott用户的四张表:

    Scott用户的四张表: 转载:http://www.cnblogs.com/mchina/archive/2012/09/06/2649951.html 在Oracle的学习之中,重点使用的是SQL ...

  6. object 类 toString() 和 equals() 的覆写

    基本作用: objiect类是所有类的父类. 任何一个类定义的时候如果没有明确定义了父类的话,默认父类是Object类. class A extends Object{} 在整个java里面,类的继承 ...

  7. UVa 231 - Testing the CATCHER

    题目大意:一种拦截导弹能拦截多枚导弹,但是它在每次拦截后高度不会再升高,给出导弹的序列,问最多能拦截多少枚导弹? 最长递减子序列问题. #include <cstdio> #include ...

  8. 4.ICMP协议,ping和Traceroute

    1.IMCP协议介绍 前面讲到了,IP协议并不是一个可靠的协议,它不保证数据被送达,那么,自然的,保证数据送达的工作应该由其他的模块来完成.其中一个重要的模块就是ICMP(网络控制报文)协议. 当传送 ...

  9. 要重定向 IO 流,Process 对象必须将 UseShellExecute 属性设置为 False。

    Process  p1= new Process(); p1.StartInfo.UseShellExecute = false;

  10. 负载均衡探测器lbd

    负载均衡探测器lbd   大型网站为了解决海量访问问题,往往采用负载均衡技术,将用户的访问分配到不同的服务器上.网站的负载均衡可以从DNS和HTTP两个环节进行实施.在进行Web渗透测试的时候,需要先 ...