ajaxfileupload
2 createUploadIframe: function (id, uri) {//id为当前系统时间字符串,uri是外部传入的json对象的一个参数
3 //create frame
4 var frameId = 'jUploadFrame' + id; //给iframe添加一个独一无二的id
5 var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; //创建iframe元素
6 if (window.ActiveXObject) {//判断浏览器是否支持ActiveX控件
7 if (typeof uri == 'boolean') {
8 iframeHtml += ' src="' + 'javascript:false' + '"';
9 } else if (typeof uri == 'string') {
10 iframeHtml += ' src="' + uri + '"';
11 }
12 }
13 iframeHtml += ' />';
14 jQuery(iframeHtml).appendTo(document.body); //将动态iframe追加到body中
15 return jQuery('#' + frameId).get(0); //返回iframe对象
16 },
17 createUploadForm: function (id, fileElementId, data) {//id为当前系统时间字符串,fileElementId为页面<input type='file' />的id,data的值需要根据传入json的键来决定
18 //create form
19 var formId = 'jUploadForm' + id; //给form添加一个独一无二的id
20 var fileId = 'jUploadFile' + id; //给<input type='file' />添加一个独一无二的id
21 var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //创建form元素
22 if (data) {//通常为false
23 for (var i in data) {
24 jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //根据data的内容,创建隐藏域,这部分我还不知道是什么时候用到。估计是传入json的时候,如果默认传一些参数的话要用到。
25 }
26 } var oldElement = jQuery('#' + fileElementId); //得到页面中的<input type='file' />对象
27 var newElement = jQuery(oldElement).clone(); //克隆页面中的<input type='file' />对象
28 jQuery(oldElement).attr('id', fileId); //修改原对象的id
29 jQuery(oldElement).before(newElement); //在原对象前插入克隆对象
30 jQuery(oldElement).appendTo(form); //把原对象插入到动态form的结尾处
31 //set attributes
32 jQuery(form).css('position', 'absolute'); //给动态form添加样式,使其浮动起来,
33 jQuery(form).css('top', '-1200px');
34 jQuery(form).css('left', '-1200px');
35 jQuery(form).appendTo('body'); //把动态form插入到body中
36 return form;
37 },
38 ajaxFileUpload: function (s) {//这里s是个json对象,传入一些ajax的参数
39 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
40 s = jQuery.extend({}, jQuery.ajaxSettings, s); //此时的s对象是由jQuery.ajaxSettings和原s对象扩展后的对象
41 var id = new Date().getTime(); //取当前系统时间,目的是得到一个独一无二的数字
42 var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //创建动态form
43 var io = jQuery.createUploadIframe(id, s.secureuri); //创建动态iframe
44 var frameId = 'jUploadFrame' + id; //动态iframe的id
45 var formId = 'jUploadForm' + id; //动态form的id
46 // Watch for a new set of requests
47 if (s.global && !jQuery.active++) {//当jQuery开始一个ajax请求时发生
48 jQuery.event.trigger("ajaxStart"); //触发ajaxStart方法
49 } var requestDone = false; //请求完成标志
50 // Create the request object
51 var xml = {}; if (s.global)
52 jQuery.event.trigger("ajaxSend", [xml, s]); //触发ajaxSend方法
53 // Wait for a response to come back
54 var uploadCallback = function (isTimeout) {//回调函数
55 var io = document.getElementById(frameId); //得到iframe对象
56 try { if (io.contentWindow) {//动态iframe所在窗口对象是否存在
57 xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null;
58 xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document;
59 } else if (io.contentDocument) {//动态iframe的文档对象是否存在
60 xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null;
61 xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document;
62 }
63 } catch (e) {
64 jQuery.handleError(s, xml, null, e);
65 } if (xml || isTimeout == "timeout") {//xml变量被赋值或者isTimeout == "timeout"都表示请求发出,并且有响应
66 requestDone = true; //请求完成
67 var status; try {
68 status = isTimeout != "timeout" ? "success" : "error"; //如果不是“超时”,表示请求成功
69 // Make sure that the request was successful or notmodified
70 if (status != "error") { // process the data (runs the xml through httpData regardless of callback)
71 var data = jQuery.uploadHttpData(xml, s.dataType); //根据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果
72 // If a local callback was specified, fire it and pass it the data
73 if (s.success)
74 s.success(data, status); //执行上传成功的操作
75 // Fire the global callback
76 if (s.global)
77 jQuery.event.trigger("ajaxSuccess", [xml, s]);
78 } else
79 jQuery.handleError(s, xml, status);
80 } catch (e) {
81 status = "error";
82 jQuery.handleError(s, xml, status, e);
83 } // The request was completed
84 if (s.global)
85 jQuery.event.trigger("ajaxComplete", [xml, s]); // Handle the global AJAX counter
86 if (s.global && ! --jQuery.active)
87 jQuery.event.trigger("ajaxStop"); // Process result
88 if (s.complete)
89 s.complete(xml, status);
90 jQuery(io).unbind();//移除iframe的事件处理程序
91 setTimeout(function () {//设置超时时间
92 try {
93 jQuery(io).remove();//移除动态iframe
94 jQuery(form).remove();//移除动态form
95 } catch (e) {
96 jQuery.handleError(s, xml, null, e);
97 }
98 }, 100)
99 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);//传入的ajax页面导向url
jQuery(form).attr('method', 'POST');//设置提交表单方式
jQuery(form).attr('target', frameId);//返回的目标iframe,就是创建的动态iframe
if (form.encoding) {//选择编码方式
jQuery(form).attr('encoding', 'multipart/form-data');
} else {
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();//提交form表单
} catch (e) {
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback); //ajax 请求从服务器加载数据,同时传入回调函数
return { abort: function () { } };
},
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 = jQuery.parseJSON(jQuery(data).text());
eval("data = " + data); // evaluate scripts within html
if (type == "html")
jQuery("<div>").html(data).evalScripts(); return data;
},
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] );
}
}
})
2 <html>
3 <head>
4 <title></title>
5 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
6 <script src="sb2/bower_components/jquery/dist/jquery.min.js"></script>
7 <script type="text/javascript" src="http://www.phpddt.com/usr/themes/dddefault/jquery-1.4.2.min.js"></script>
8 <script type="text/javascript" src="js/ajaxfileupload.js"></script>
9 </head>
<script>
jQuery(function () {
$("#buttonUpload").click(function () {
//加载图标
/* $("#loading").ajaxStart(function(){
$(this).show();
}).ajaxComplete(function(){
$(this).hide();
});*/
//上传文件
$.ajaxFileUpload({
url: 'resuser/fileUpload.do',//处理图片脚本
secureuri: false,
fileElementId: 'fileToUpload',//file控件id
dataType: 'json',
success: function (data, status) {
var dUrl = "resuser/fileDownload.do?filename=" + data.data.fileName;
$("#fileUrl").attr({href: dUrl});
alert(status);
},
error: function (data, status, e) {
alert(status);
}
})
return false;
});
})
</script>
<body>
<input id="fileToUpload" type="file" size="20" name="fileToUpload" class="input">
<button id="buttonUpload">上传</button>
<a id="fileUrl">查看上传附件</a>>
</body>
44 </html>
如遇到IE 需要保存json的问题,后端配置需要改
今天用ajaxFileUpload做了一个读取图片EXIF信息然后上传到服务器的功能。
因为读取是在后台读取的,所以先上传了一次。
后来发现读取完成以后,再上传的时候file为空,没有文件信息。
网上查资料也找不到解决办法。
后来看ajaxFileUpload源码,发现创建from的时候没有保留原file的file信息。
解决方法:
在ajaxFileUpload.js源码中找到:createUploadForm 找到这一段
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
改为:
var oldElement = jQuery('#' + fileElementId);
var newElement = oldElement.clone(true);
newElement[0].files=oldElement[0].files;
oldElement.attr('id', fileId);
oldElement.before(newElement);
oldElement.appendTo(form);
ajaxfileupload的更多相关文章
- ajaxFileUpload插件
关键词: $.ajaxFileUpLoad(); data status dataType 参考资料: http://www.cnblogs.com/kissdodog/archive/2012/12 ...
- .NET MVC实现多图片上传并附带参数(ajaxfileupload)
做网站呢,都免不了要做图片上传. 还记得去年做微信的时候用WebAPI+ajaxfileupload.js做了一个能够附带参数上传的功能,博文地址:.NET WebAPI 实现图片上传(包括附带参数上 ...
- ajaxFileupload多文件上传
最近有个功能模块需要上传图片,为了和之前的伙伴们保持一致我也使用了ajaxFileupload, 但是源码只支持单文件上传,所以百般斟酌之下决定修改源码,废话不多说直接上代码 HTML上传代码段: & ...
- 使用ajaxfileupload.js实现上传文件功能
<div class="pictureList"> <div class="pictureItem" id="uploadItem& ...
- PHP+ajaxfileupload与jcrop插件结合 完成头像上传
昨天花了点时间整合了一下头像插件 东拼西凑的成果 先来看下效果
- jQuery插件之ajaxFileUpload异步上传
介绍 AjaxFileUpload.js 是一个异步上传文件的jQuery插件,原理是创建隐藏的表单和iframe然后用JS去提交,获得返回值. 下载地址: http://files.cnblogs. ...
- JQuery文件上传插件ajaxFileUpload在Asp.net MVC中的使用
0 ajaxFileUpload简介 ajaxFileUpload插件是一个非常简单的基于Jquery的异步上传文件的插件,使用过程中发现很多与这个同名的,基于原始版本基础之上修改过的插件,文件版本比 ...
- <<< ajaxfileupload介绍
ajaxfileupload,jquery的一个异步上传插件,使用此插件你可以不用建立form,他会自动生成表单,且自动设置好enctype="multipart/form-data&quo ...
- <<< commons-fileupload 和 ajaxfileupload 实现局部上传
最近弄了一个上传,要求实现页面的局部刷新,Java的上传组件大多还是用的 commons-fileupload,网上搜索了好多的教程,太麻烦了,看到了ajaxfileupload这个插件,不错,实现简 ...
- struts2 jquery ajaxFileUpload 异步上传文件
网上搜集的,整理一下. 一.ajaxFileUpload 实现异步上传文件利用到了ajaxFileUpload.js这个文件,这是别人开发的一个jquery的插件,可以实现文件的上传并能够和strut ...
随机推荐
- poj Cash Machine
http://poj.org/problem?id=1276 #include<cstdio> #include<cstring> #include<cmath> ...
- java.lang.NoClassDefFoundError: javax/servlet/ServletContext
方法1:把SpringBoot中main方法所在的class不再继承org.springframework.boot.context.web.SpringBootServletInitializer即 ...
- 【翻译】Organizing ASP.NET MVC solutions 如何组织你的ASP.NET MVC解决方案
序言 时隔一年,弦哥重出江湖,对于我们学习.NET MVC那将有大大的好处,期待弦哥的重构系列.在弦哥与jerrychou的交流中提到了一篇文章http://lostechies.com/jimmyb ...
- Word Ladder——LeetCode
Given two words (start and end), and a dictionary, find the length of shortest transformation sequen ...
- [Design Pattern] Iterator Pattern 简单案例
Iterator Pattern,即迭代时模式,按照顺序依次遍历集合内的每一个元素,而不用了解集合的底层实现,属于行为类的设计模式.为了方便理解记忆,我也会称其为遍历模式. 下面是一个迭代器模式的简单 ...
- linux命令详解--tcpdump
工作中一直在用tcpdump,感觉非常方便,今天心血来潮百度了一下tcpdump的用法,才发现原来还有这么多强大的功能自己都不知道,那叫一个汗啊. 以此文作为备份,记录一些新知道的用法,各位网友谁有新 ...
- JDKSDK配置
变量名:ANDROID_HOME 变量值: E:\android-sdk_r11-windows\android-sdk_r11-windowsclsspath .;%JAVA_HOME%\l ...
- Android应用程序之间共享文字和图片(一)
以下为TestReceiveShare1工程 MainActivity如下: package cn.testreceiveshare1; import java.util.ArrayList; imp ...
- css实现鼠标移上去变大,旋转,转别人的额
<!doctype html><html><head> <meta charset="utf-8"> <title>CS ...
- OD: DEP - Ret2Libc via VirtualProtect() & VirtualAlloc()
一,通过 VirutalProtect() 修改内存属性绕过 DEP DEP 的四种工作模式中,OptOut 和 AlwaysOn 下所有进程默认都开启 DEP 保护,这里如果一个程序自身需要从堆栈中 ...