Spring Java ajaxfileupload.js 上传头像 2.0

1.0版,实现功能:预览+上传头像

Spring Java 上传头像 - qq_24435837的博客 - 博客频道 - CSDN.NET  

http://blog.csdn.net/qq_24435837/article/details/52460855

2.0版,增加功能:IE浏览器预览+校验

IE真是吐血,尤其是我由于一些原因打开的页面全变成了IE9兼容性视图,关于这一部分看这里:

关于IE兼容,发布后变成了IE9(浏览器IE9兼容模式,文档IE7标准模式) - qq_24435837的博客 - 博客频道 - CSDN.NET
http://blog.csdn.net/qq_24435837/article/details/52729907

中间碰到的问题:

jQuery1.9以上判断浏览器类型已经不支持Browser了:

解决jquery1.9不支持browser对象的问题_jquery_脚本之家
http://www.jb51.net/article/43176.htm

我还是改了判断浏览器类型的方式:

js:

    var ua = window.navigator.userAgent;  

     if (ua.indexOf("MSIE")>=1){ 
         browserCfg.ie = true;  
     }else if(ua.indexOf("Firefox")>=1){
         browserCfg.firefox = true;  
     }else if(ua.indexOf("Chrome")>=1){  
         browserCfg.chrome = true;  
     }else if (!!window.ActiveXObject || "ActiveXObject" in window){
         browserCfg.ie = true; 
     }

js代码判断浏览器种类IE、FF、Opera、Safari、chrome及版本_javascript技巧_脚本之家
http://www.jb51.net/article/50464.htm

ajaxfileUpload.js:

需要把(jQuery.browser.version)改成($.support.leadingWhitespace)

一,ajaxfileUpload.js兼容ie7、8、9、10、11、firefox、chrome等浏览器的js代码 - 一个人不旅行的日志 - 网易博客
http://yanghelinok.blog.163.com/blog/static/46360272201492233014408/

二,jQuery 1.9使用$.support替代$.browser的使用方法_jquery_脚本之家
http://www.jb51.net/article/50463.htm

IE浏览器预览

查了很多资料都是说镜像预览,但是这样预览不了gif啊

首先镜像预览:

 if(browserCfg.ie){ 
         obj.select();
         url = document.selection.createRange().text;      
         $("#preview").hide();
    	 $("#previewIE").show();
    	 var timeStamp = (new Date()).valueOf();
    	 document.selection.empty();     
    	 document.getElementById("previewIE").style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src='"+url+ "?t=" + timeStamp+"')";         	

  }
其中$("#preview")为<img>标签,$("#previewIE")为 <div>标签,因为镜像根本赋值不到img标签里啊,反而会是一个错误图片的样子

一,IE9 js图片预览 可设定显示出来的图片大小 - funi16的专栏 - 博客频道 - CSDN.NET
http://blog.csdn.net/funi16/article/details/8222813

二,ie9可以实现在上传图片时预览图片么?-CSDN论坛-CSDN.NET-中国最大的IT技术社区
http://bbs.csdn.net/topics/380206804

三,input file本地图片预览的方法(兼容IE、Chrome和Firefox)_JavaScript_西部e网
http://www.weste.net/2013/5-8/91102.html
由于gif无法预览,只能先上传到服务器,取服务器上的URL再显示出来


校验:

IE浏览器在js校验文件大小是行不通的!上传到后台,后台校验后再把信息返回给前台

java:

if(myfile.getSize() <= 1*1024*1024)
值得注意的是,之前1.0里我配了spring,得把其中的<property name="maxUploadSize" value="800000"/>删了,否则超过800000大小的直接被这里拦截了

以及这里的id="multipartResolver"比较特殊,一定不要删除

(小心 Spring MVC 使用陷阱 - MONKEYK - 博客频道 - CSDN.NET      http://blog.csdn.net/monkeyking1987/article/details/19022387)

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!-- 指定所上传文件的总大小不能超过800KB......注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->  
        <property name="maxUploadSize" value="800000"/>  
    </bean> 

js:

这里的data一定要处理的,因为data为空时返回的是<pre>这种东西,而不是null或者" "

$.ajaxFileUpload({
    			TYPE : "POST",
    			url : "uploadImage", 
    			secureuri : false, 
    			dataType : "text/html", 
    			fileElementId : "imagefile",
    			success: function(data){
    				data = data.replace(/<pre.*?>/g, '');  
    	            <span style="white-space:pre">		</span>data = data.replace(/<PRE.*?>/g, '');  
    	           <span style="white-space:pre">		</span>data = data.replace("<PRE>", '');  
    	            <span style="white-space:pre">		</span>data = data.replace("</PRE>", '');  
    	            <span style="white-space:pre">		</span>data = data.replace("<pre>", '');  
    	           <span style="white-space:pre">		</span>data = data.replace("</pre>", '');
    				if(data == null || data == ""){
    					flagImg = false;
    			 		$("#errorTip").text("请选择正确的图片大小");
    				}else{
    					flagImg = true;
    					var timeStamp = (new Date()).valueOf();			
    					$("#preview").attr('src',data + "?t=" + timeStamp);				
    				}			
    			},  
    		});

其他浏览器js校验文件大小与预览:

$('#imagefile')为打开文件的input标签,$("#preview")和previewUrl是我要预览的两个地方(参考1.0)

 if(browserCfg.firefox || browserCfg.chrome ){  
         filesize =  $('#imagefile')[0].files[0].size;
         url = window.URL.createObjectURL($('#imagefile')[0].files[0]);
         $("#preview").attr("src",url);       		 
 	 $("#errorTip").text("");
 	 if(filesize==-1 || filesize>maxsize){  
 		flagImg = false;
 		$("#errorTip").text("请选择正确的图片大小");   
 		return;  
 	  }else{
 		previewUrl = url;
 	  } 
     }
校验图片格式:

这个是所有浏览器通用的:

     var filepath = $("#imagefile").val(); 
     var filetypes =[".jpg",".gif",".png",".jpeg",".bmp"];          

     if(filepath){ 
    	 var isnext = false; 
    	 var fileEnd = filepath.substring(filepath.indexOf(".")); 
    	 	if(filetypes && filetypes.length>0){ 
    	 		for(var i =0; i<filetypes.length;i++){ 
    	 			if(filetypes[i]==fileEnd){ 
    	 				isnext = true; 
    	 				break; 
    	 			} 
    	 		} 
    	 	} 
    	 	if(!isnext){
    	 		flagImg = false;
    	 		$("#errorTip").text("请选择正确的图片格式");  
    	 		return false; 
    	 	} 
     }else{ 
    	 return false; 
     } 


我用的ajaxfileupload.js:

// JavaScript Document
jQuery.extend({

createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;

if(window.ActiveXObject) {
//var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if($.support.leadingWhitespace){ 
var io = document.createElement('iframe'); 
io.id = frameId; 
io.name = frameId; 
}else if(!$.support.leadingWhitespace){ 
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; 
},
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>'); 
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);

//add data
if(data) { 
for (var i in data) { 
$('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').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 = s.id; 
//var id = s.fileElementId; 
var form = jQuery.createUploadForm(id, s.fileElementId,s.data);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id; 

if( s.global && ! jQuery.active++ ){
// Watch for a new set of requests
jQuery.event.trigger( "ajaxStart" );
} 
var requestDone = false;
// Create the request object
var xml = {}; 
if( s.global ){
jQuery.event.trigger("ajaxSend", [xml, s]);
} 

var uploadCallback = function(isTimeout){ 
// Wait for a response to come back 
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( s.success ){
// ifa local callback was specified, fire it and pass it the data
s.success( data, status );
}; 
if( s.global ){
// Fire the global callback
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
}; 
} else{
jQuery.handleError(s, xml, status);
}

} catch(e){
status = "error";
jQuery.handleError(s, xml, status, e);
}; 
if( s.global ){
// The request was completed
jQuery.event.trigger( "ajaxComplete", [xml, s] );
};

// Handle the global AJAX counter
if(s.global && ! --jQuery.active){
jQuery.event.trigger("ajaxStop");
};
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(){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){
form.encoding = 'multipart/form-data'; 
}else{ 
form.enctype = 'multipart/form-data';
} 
jQuery(form).submit();

} catch(e){ 
jQuery.handleError(s, xml, null, e);
}
/*if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
} */
jQuery('#' + frameId).load(uploadCallback);
return {abort: function () {}}; 

},

uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// ifthe type is "script", eval it in global context
if( type == "script" ){
jQuery.globalEval( data );
}

// Get the JavaScript object, ifJSON 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] );
}*/
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] );
}
}
});













  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值