$.ajaxFileUpload上传文件出现错误...问题总结
2017-03-22 14:13
555 查看
1、 加载报错: ajaxfileupload.js:1 Uncaught ReferenceError: jQuery is not defined
上传报错: Uncaught TypeError: $.ajaxFileUpload is not a function
原因: jquery.js,ajaxfileupload.js加载顺序不正确,应先加载 jquery.js,再加载ajaxfileupload.js
2、 运行时报错: jQuery.handleError is not a function
原因: ajaxfileupload.js插件中使用低版本jquery,版本1.4.2之前的版本才有handlerError方法,例子里使用的Jquery是1.2的,需手动添加该方法
3、 执行成功后,始终指向error方法处理,无法执行sucess方法
原因: 这个是由于ajaxfileupload.js 处理返回data的时候,没有考虑后台返回的是字符串的问题,data数据被加了pre标签了。。。
4、不报错,但是图片上传不成功,显示到ajaxfileupload.js中 jQuery(form).submit();//提交form表单 这里
原因: 后台处理文件上传时,指定的存储路径不正确
示例:
file.blade.php
ajaxfileupload.js
fileController.php
示例效果如图:
上传报错: Uncaught TypeError: $.ajaxFileUpload is not a function
原因: jquery.js,ajaxfileupload.js加载顺序不正确,应先加载 jquery.js,再加载ajaxfileupload.js
<script type="text/javascript" src="jquery.js"></script> <script src="ajaxfileupload.js" type="text/javascript"></script>
2、 运行时报错: jQuery.handleError is not a function
原因: ajaxfileupload.js插件中使用低版本jquery,版本1.4.2之前的版本才有handlerError方法,例子里使用的Jquery是1.2的,需手动添加该方法
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] ); } }
3、 执行成功后,始终指向error方法处理,无法执行sucess方法
原因: 这个是由于ajaxfileupload.js 处理返回data的时候,没有考虑后台返回的是字符串的问题,data数据被加了pre标签了。。。
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=data.replace("<pre>","").replace("</pre>",""); //如果返回的是字符串(JSON格式字符串),去除pre标签 data=eval('(' + data+ ')'); // evaluate scripts within html return data; if (type == "html") jQuery("<div>").html(data).evalScripts(); return data; }
4、不报错,但是图片上传不成功,显示到ajaxfileupload.js中 jQuery(form).submit();//提交form表单 这里
原因: 后台处理文件上传时,指定的存储路径不正确
示例:
file.blade.php
<script type="text/javascript" src="jquery.js"></script> <script src="ajaxfileupload.js" type="text/javascript"></script>
缩略图:<input type="file" id="file_upload" name="file_upload" onchange="savethumb('thumb')" />
<input type="hidden" id="thumb" name="thumb" />
<img src="" id="thumb_img" style="width:150px;height:150px;" />
ajaxfileupload.js
jQuery.extend({
createUploadIframe: function (id, uri) {//id为当前系统时间字符串,uri是外部传入的json对象的一个参数
//create frame
var frameId = 'jUploadFrame' + id; //给iframe添加一个独一无二的id
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"'; //创建iframe元素
if (window.ActiveXObject) {//判断浏览器是否支持ActiveX控件
4000
if (typeof uri == 'boolean') {
iframeHtml += ' src="' + 'javascript:false' + '"';
} else if (typeof uri == 'string') {
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body); //将动态iframe追加到body中
return jQuery('#' + frameId).get(0); //返回iframe对象
},
createUploadForm: function (id, fileElementId, data) {//id为当前系统时间字符串,fileElementId为页面<input type='file' />的id,data的值需要根据传入json的键来决定
//create form
var formId = 'jUploadForm' + id; //给form添加一个独一无二的id
var fileId = 'jUploadFile' + id; //给<input type='file' />添加一个独一无二的id
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>'); //创建form元素
if (data) {//通常为false
for (var i in data) {
if (data[i] instanceof Array) {
for ( var j in data[i]) {
jQuery('<input type="checkbox" name="'+i+'" value="'+data[i][j]+'" checked />').appendTo(form);
}
} else {
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form); //根据data的内容,创建隐藏域,这部分我还不知道是什么时候用到。估计是传入json的时候,如果默认传一些参数的话要用到。
}
}
}
if (fileElementId instanceof Array) {
for (var i = 0; i < fileElementId.length; i++) {
var oldElement = jQuery('#' + fileElementId[i]); //得到页面中的<input type='file' />对象
var newElement = jQuery(oldElement).clone(); //克隆页面中的<input type='file' />对象
jQuery(oldElement).attr('id', fileElementId[i]); //修改原对象的id
jQuery(oldElement).before(newElement); //在原对象前插入克隆对象
jQuery(oldElement).appendTo(form); //把原
}
} else {
var oldElement = jQuery('#' + fileElementId); //得到页面中的<input type='file' />对象
var newElement = jQuery(oldElement).clone(); //克隆页面中的<input type='file' />对象
jQuery(oldElement).attr('id', fileId); //修改原对象的id
jQuery(oldElement).before(newElement); //在原对象前插入克隆对象
jQuery(oldElement).appendTo(form); //把原对象插入到动态form的结尾处
}
//set attributes
jQuery(form).css('position', 'absolute'); //给动态form添加样式,使其浮动起来,
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body'); //把动态form插入到body中
return form;
},
ajaxFileUpload: function (s) {//这里s是个json对象,传入一些ajax的参数
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s); //此时的s对象是由jQuery.ajaxSettings和原s对象扩展后的对象
var id = new Date().getTime(); //取当前系统时间,目的是得到一个独一无二的数字
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data)); //创建动态form
var io = jQuery.createUploadIframe(id, s.secureuri); //创建动态iframe
var frameId = 'jUploadFrame' + id; //动态iframe的id
var formId = 'jUploadForm' + id; //动态form的id
// Watch for a new set of requests
if (s.global && !jQuery.active++) {//当jQuery开始一个ajax请求时发生
jQuery.event.trigger("ajaxStart"); //触发ajaxStart方法
} var requestDone = false; //请求完成标志
// Create the request object
var xml = {}; if (s.global)
jQuery.event.trigger("ajaxSend", [xml, s]); //触发ajaxSend方法
// Wait for a response to come back
var uploadCallback = function (isTimeout) {//回调函数
var io = document.getElementById(frameId); //得到iframe对象
try { if (io.contentWindow) {//动态iframe所在窗口对象是否存在
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) {//动态iframe的文档对象是否存在
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") {//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); //根据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果
// 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();//移除iframe的事件处理程序
setTimeout(function () {//设置超时时间
try {
jQuery(io).remove();//移除动态iframe
jQuery(form).remove();//移除动态form
} 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);//传入的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=data.replace("<pre>","").replace("</pre>","");//除去字符串中的pre标签
data=eval('(' + data+ ')'); // evaluate scripts within html
return data;
if (type == "html")
jQuery("<div>").html(data).evalScripts(); return data;
},
//自添加方法handleError
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] ); } }
})
fileController.php
/* * 上传图片 */ public function postUpload(){ if(!isset($_FILES['file_upload'])){ echo json_encode(array('err'=>"找不到该文件")); die; }else{ $news_filename = $_FILES['file_upload']['name']; $news_fileext = get_filetype($news_filename); $middle_name = date('YmdHis',time()).rand(1000,9999); if(!in_array($news_fileext, array('jpg', 'gif', 'png'))){ echo json_encode(array('err' => '请上传JPG、GIF、PNG格式图片文件')); die; } $FileName = $middle_name.'.'.$news_fileext; $Path = "/uploadfile/images/".date('Ymd',time()); $imgPath = ROOT_DIR.'/'.$Path;//***公共文件夹访问目录*** if(!file_exists($imgPath))mkdirs($imgPath); $news_filesize = filesize($_FILES['file_upload']['tmp_name']); if($news_filesize>20*1024*1024){ echo json_encode(array('err'=>'文件过大'));die; } move_uploaded_file($_FILES['file_upload']['tmp_name'], $imgPath.DS.$FileName); $json = array('filepath' => $Path.'/'.$FileName); echo json_encode($json); die; } }
示例效果如图:
相关文章推荐
- ajax图片上传及时回显图片,自己总结 + ajaxFileUpload 上传文件 以及 返回值 带 <pre> 标签问题
- Ajaxfileupload 上传文件后返回response的contentType错误问题
- ajaxfileupload上传文件出现SyntaxError:unexpected token <错误
- 使用ajaxfileupload.js进行文件上传,出现的问题以及解决办法
- 后台使用Spring MVC 4.15 版本 通过 ajaxFileUpload plugin插件上传文件相应时引起的一个小问题,Chrome、Firefox中出现SyntaxError:unexpected token <
- ajaxfileupload上传文件出现SyntaxError:unexpected token <错误
- flex文件上传filereference.upload出现Error #2038: 文件 I/O 错误。
- ajaxFileUpload 上传文件/图片,传参数,解决第二次无法上传问题
- spring mvc 下使用ajaxfileupload.js 异步上传文件 并返回信息 各种问题解决
- 上传文件中使用ajaxfileupload.js碰到的问题
- 上传文件总结--使用springMVC+ajaxfileupload.js
- ajaxfileUpload.js 上传文件 IE浏览器提示下载json的问题
- ajaxFileUpload plugin上传文件 chrome、Firefox中出现SyntaxError:unexpected token <
- ajaxFileUpload上传文件后提示下载的问题
- ajaxFileUpload plugin上传文件 chrome、Firefox中出现SyntaxError:unexpected token <
- springMVC+Ajaxfileupload无刷新上传文件返回json串问题
- ajaxFileUpload 上传文件 以及 返回值 带 <pre> 标签问题
- ajaxfileUpload.js 异步文件上传 onchange问题
- ajaxFileUpload上传文件时IE浏览器弹出下载提示问题处理
- asp.net结合ajaxfileupload控件上传文件一直提示undefined问题