AjaxFileUpload.js是网络开发者写好的插件放出来供大家使用用,原理都是创建隐藏的表单和iframe然后用JS去提交,获得返回值。在这里我将网络上下载下来的插件包进行了修改,以实现多文件上传功能,下面我给大家讲解一下该插件的用法 。
改写后的插件源码(使用的时候将插件源码拷贝到您新建的js文件中保存,然后对js文件进行引用):
jQuery.extend({
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]);
}
},
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) {
//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);
}
}
var oldElement = typeof fileElementId == "string" ? jQuery('#' + fileElementId) : fileElementId;
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));
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 () { } };
},
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")
eval("data = " + data);
// evaluate scripts within html
if (type == "html")
jQuery("<div>").html(data).evalScripts();
return data;
}
})
语法:$.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直接打印的方法检查各参数是否正确,比起上面这些无效的错误提示还是方便很多。
使用方法:
Step 1:先引入jQuery与ajaxFileUpload插件。(在这里要注意引入的先后顺序)
<script src="jquery-1.7.1.js" type="text/javascript"></script>
<script src="ajaxfileupload.js" type="text/javascript"></script>
Step 2:HTML代码
<input type="file" onchange="ajaxFileUpload();" class="input-text" id="cat_img" name="cat_img">
<input type="hidden" name="mark_img_id" id="mark_img_id" value="" />
<img src="" id="show_mark_img" style="max-height: 120px;" />
Step 3:JS代码,下面是我封装的一个上传文件的方法
function ajaxFileUpload() {
//判断当前文件表单中ID的值是否为空,如果不为空,则进行保存
var tmp = $("#mark_img_id").val();
if(tmp == ''){
var oldTmp = $("#old_mark_img_arr").val(tmp);
$("#old_mark_img_arr").val(oldTmp+','+tmp);
}
var inputFile = $("#cat_img > input:file")[0];
$.ajaxFileUpload({
url: '/Admin/System/fileUpload.html', //用于文件上传的服务器端请求地址
fileElementId: "cat_img", //文件上传域的ID
dataType: 'text', //返回值类型 一般设置为json
success: function(data, status) //服务器成功响应处理函数
{
if(data==false){
alert("上传文件出现异常!");
return false;
}
//这里是对返回数据的处理,以下写法是我个人的写法,依实际情况对返回的数据进行处理
var jsonArr = data.split('>');
jsonArr = jsonArr[1].split('<');
var arr = jQuery.parseJSON(jsonArr[0]);
$("#show_mark_img").attr("src",arr[0]['url']);
$("#mark_img_id").val(arr[0]['id']);
},
error: function(data, status, e) //服务器响应失败处理函数
{
if(data==false){
alert("上传头像出现异常!");
return false;
}
},
complete: function() {
var jq = $("#file1 > input:file");
jq.before(inputFile);
jq.remove();
}
});
};
Step 4:后台的处理程序这里就不写了,最后返回相应的数据即可,本站其它文章中有讲到服务器端文件接收与参数返回,不懂的朋友可以到本站查找学习。
具体用法到这里就讲完了,我这里实现的效果图片如下:
版权声明: 此文为本站源创文章[或由本站编辑从网络整理改编], 转载请备注出处:http://www.sindsun.com/article-details-18.html [若此文确切存在侵权,请联系本站管理员进行删除!]