Js 压缩图片 ajax 上传

一 /* 图片上传方法开始 /
/

三个参数
file:一个是文件(类型是图片格式),
w:一个是文件压缩的后宽度,宽度越小,字节越小
objDiv:一个是容器或者回调函数
photoCompress()
/
function photoCompress(file,w,objDiv){
var ready=new FileReader();
/开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容./
ready.readAsDataURL(file);
ready.οnlοad=function(){
var re=this.result;
canvasDataURL(re,w,objDiv)
}
}
function canvasDataURL(path, obj, callback){
var img = new Image();
img.src = path;
img.onload = function(){
var that = this;
// 默认按比例压缩
var w = that.width,
h = that.height,
scale = w / h;
w = obj.width || w;
h = obj.height || (w / scale);
var quality = 0.7; // 默认图片质量为0.7
//生成canvas
var canvas = document.createElement(‘canvas’);
var ctx = canvas.getContext(‘2d’);
// 创建属性节点
var anw = document.createAttribute(“width”);
anw.nodeValue = w;
var anh = document.createAttribute(“height”);
anh.nodeValue = h;
canvas.setAttributeNode(anw);
canvas.setAttributeNode(anh);
ctx.drawImage(that, 0, 0, w, h);
// 图像质量
if(obj.quality && obj.quality <= 1 && obj.quality > 0){
quality = obj.quality;
}
// quality值越小,所绘制出的图像越模糊
var base64 = canvas.toDataURL(‘image/jpeg’, quality);
// 回调函数返回base64的值
callback(base64);
}
}
/
*
* 将以base64的图片url数据转换为Blob
* @param urlData
* 用url方式表示的base64图片数据
/
function convertBase64UrlToBlob(urlData){
var arr = urlData.split(’,’), mime = arr[0].match(/?.
?);/)[1],
bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while(n–){
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {type:mime});
}

			var xhr;


			//上传文件方法
			function ajaxFileUpload() {
				var id = file1;
				var fileObj = document.getElementById("file1").files[0];
				
			  
			    var url = "                 "; // 接收上传文件的后台地址 

			    var form = new FormData(); // FormData 对象

			    if(fileObj.size/1024 > 1025) { //大于1M,进行压缩上传
			        photoCompress(fileObj, {
			            quality: 0.2
			        }, function(base64Codes){
			            //console.log("压缩后:" + base.length / 1024 + " " + base);
			            var bl = convertBase64UrlToBlob(base64Codes);
			            form.append("file", bl, "file_"+Date.parse(new Date())+".jpg"); // 文件对象
			            xhr = new XMLHttpRequest();  // XMLHttpRequest 对象
			            xhr.open("post", url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。
			            xhr.onload = function(evt){
			            	var text1= evt.target.responseText;
			          	  
			                console.log()
			            	var str = eval("("+text1.split("}")[0]+"}"+")");
			                if(str.Success=="1") {
			                    alert("上传成功!");
			                    var _imgUrl = str.URL;
								/* $(".simditor-body").html($(".simditor-body").html() + "<p><img id='woyu' class='myimg' src='" + _imgUrl + "' style='max-width:800px;height:auto;'/></p>"); //把图片添加到文本域中
								//                      	
								_editor.sync(); //将编辑器的正文内容同步到 textarea 元素的 val 属性,返回值为编辑器正文的 HTML 内容。
								$("#mmb").css("display","none");
								alert("成功啦") */
								if($(".simditor-body .child_text").first().text()==""){
									$(".simditor-body .child_text").first().remove();
								}
								var _imgUrl = str.URL;
								var isMyImg="<img style='width:265px;margin-left: 5px;cursor: pointer;' onclick='window.open(\"" + _imgUrl + "\")' src=" + _imgUrl + " />";
								if($(".simditor-body .miniu:last").find("img").length>2||$(".simditor-body .miniu:last").find("img").length==0){
									$(".simditor-body ").append('<p class="miniu">'+isMyImg+'</p>');
								}else{
									$(".simditor-body").find(".miniu:last").append(isMyImg);
								}
			                }else{
			                    alert("上传失败!");
			                }}; //请求完成
			            xhr.onerror =  uploadFailed; //请求失败

			           /*  xhr.upload.onprogress = progressFunction;//【上传进度调用方法实现】
			            xhr.upload.onloadstart = function(){//上传开始执行方法
			                ot = new Date().getTime();   //设置上传开始时间
			                oloaded = 0;//设置上传开始时,以上传的文件大小为0
			            };
			 */
			            xhr.send(form); //开始上传,发送form数据
			        });
			    }else{ //小于等于1M 原图上传
			        form.append("file", fileObj); // 文件对象
			        xhr = new XMLHttpRequest();  // XMLHttpRequest 对象
			        xhr.open("post", url, true); //post方式,url为服务器请求地址,true 该参数规定请求是否异步处理。
			        xhr.onload = function(evt){
			        	var text1= evt.target.responseText;
			        	  
			            console.log()
			        	var str = eval("("+text1.split("}")[0]+"}"+")");
			            if(str.Success=="1") {
			                alert("上传成功!");
			                var _imgUrl = str.URL;
							/* $(".simditor-body").html($(".simditor-body").html() + "<p><img id='woyu' class='myimg' src='" + _imgUrl + "' style='max-width:800px;height:auto;'/></p>"); //把图片添加到文本域中
							//                      	
							_editor.sync(); //将编辑器的正文内容同步到 textarea 元素的 val 属性,返回值为编辑器正文的 HTML 内容。
							$("#mmb").css("display","none");
							alert("成功啦") */
							if($(".simditor-body .child_text").first().text()==""){
								$(".simditor-body .child_text").first().remove();
							}
							var _imgUrl = str.URL;
							var isMyImg="<img style='width:265px;margin-left: 5px;cursor: pointer;' onclick='window.open(\"" + _imgUrl + "\")' src=" + _imgUrl + " />";
							if($(".simditor-body .miniu:last").find("img").length>2||$(".simditor-body .miniu:last").find("img").length==0){
								$(".simditor-body ").append('<p class="miniu">'+isMyImg+'</p>');
							}else{
								$(".simditor-body").find(".miniu:last").append(isMyImg);
							}
			            }else{
			                alert("上传失败!");
			            }
			        }; //请求完成
			        xhr.onerror =  uploadFailed; //请求失败

			        //xhr.upload.onprogress = progressFunction;//【上传进度调用方法实现】
			        xhr.upload.onloadstart = function(){//上传开始执行方法
			            ot = new Date().getTime();   //设置上传开始时间
			            oloaded = 0;//设置上传开始时,以上传的文件大小为0
			        };

			        xhr.send(form); //开始上传,发送form数据
			    }
			}

			//上传成功响应
			function uploadComplete(evt) {
			    //服务断接收完文件返回的结果
			var text1= evt.target.responseText;
			  
			    console.log()
				var str = eval("("+text1.split("}")[0]+"}"+")");
			    if(str.Success=="1") {
			        alert("上传成功!");
			       if($("#"+id+" .child_text").first().text()==""){
						$(".simditor-body .child_text").first().remove();
					}
					var _imgUrl = str.URL;
					var isMyImg="<img style='width:265px;margin-left: 5px;cursor: pointer;' onclick='window.open(\"" + _imgUrl + "\")' src=" + _imgUrl + " />";
					if($("#"+id+"  .miniu:last").find("img").length>2||$("#"+id+" .miniu:last").find("img").length==0){
						$("#"+id).append('<p class="miniu">'+isMyImg+'</p>');
					}else{
						
						$("#"+id).find(".miniu:last").append(isMyImg);
					} 
			    }else{
			        alert("上传失败!");
			    }

			}
			//上传失败
			function uploadFailed(evt) {
			    alert("上传失败!");
			}
			//取消上传
			function cancleUploadFile(){
			    xhr.abort();
			}
			/* 图片上传方法结束  */

二 附一个小例子

XMLHttpRequest上传文件

笔记:

插图
function file1Click(id){ $("#"+id).click(); //直接调用 ajaxFileUpload 这个方法 }

ajaxFileUpload()

三 另外一种上传图片的方法 不经过压缩 实现ajax无刷新上传 弊端 图片大的时候 比如大于5m就上传不了了 需要引入 ajaxfileupload.js.
function ajaxFileUpload(id) {
KaTeX parse error: Expected '}', got '&' at position 75: …?Filepath=1.png&̲IsFLM=false&Use…("#"+id+" .child_text").first().text()""){
KaTeX parse error: Expected 'EOF', got '}' at position 54: ….remove(); }̲ var _imgUr…("#"+id+" .miniu:last").find(“img”).length>2||$("#"+id+" .miniu:last").find(“img”).length
0){
$("#"+id).append(’

’+isMyImg+’

’);
}else{
$("#"+id).find(".miniu:last").append(isMyImg);
}
}
	},
	error: function (data, status, e)//服务器响应失败处理函数
	{	
		
		alert(e);
	}
});
return false;

}
取自这里

ajaxfileupload.js 如下

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(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)
{
    //create form
    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);
    //set attributes
    $(form).css('position', 'absolute');
    $(form).css('top', '-1200px');
    $(form).css('left', '-1200px');
    $(form).appendTo('body');
    return form;
},
addOtherRequestsToForm: function(form,data)
{
    // add extra parameter
    var originalElement = $('<input type="hidden" name="" value="">');
    for (var key in data) {
        name = key;
        value = data[key];
        var cloneElement = originalElement.clone();
        cloneElement.attr({'name':name,'value':value});
        $(cloneElement).appendTo(form);
    }
    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);
    if ( s.data ) form = jQuery.addOtherRequestsToForm(form,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
                {
                    $(io).remove();
                    $(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 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.handleError(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 ) {
    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" )
    {
        // If you add mimetype in your response,
        // you have to delete the '<pre></pre>' tag.
        // The pre tag in Chrome has attribute, so have to use regex to remove
        var data = r.responseText;
        var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
        var am = rx.exec(data);
        //this is the desired data extracted
        var data = (am) ? am[1] : "";    //the only submatch or empty
        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;
},

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、付费专栏及课程。

余额充值