關於 javascript抓取網絡圖片轉成file上傳

 關於 javascript抓取網絡圖片轉成file上傳


    var c = document.createElement("canvas");
    var cxt=c.getContext("2d");
    var img=new Image();
    img.setAttribute("crossOrigin",'Anonymous');
    img.onload=function(){
        var fileIndex=this.src.lastIndexOf("/");
        var filename= this.src.substr(fileIndex+1);

        c.width = this.width;
        c.height = this.height;
        cxt.drawImage(img, 0, 0, this.width, this.height) // 在canvas上繪製圖片
        var dataURL = compress(img,this.width,this.height,0.8);
        /*爲了兼容ios 需要 dataURL-> blob -> file */
        var blob = dataURLtoBlob(dataURL);		// dataURL-> blob
        var file = blobToFile(blob, filename);		// blob -> file
        console.log("得到文件:"+file);
        console.log("壓縮後大小:"+file.size/1024);


        var fd = new FormData();
        fd.append("upfile",file  ,filename);
        //fd.append("files",file ,filename);
        $.ajax({
            //url: 'http://127.0.0.1:8080/base/file/upload',
            url:'http://127.0.0.1:8081/ueditor/config?action=uploadimage',
            type : 'POST',
            dataType : 'json',
            cache : false,
            contentType : false,//(必須這樣配置)
			processData : false,    //JQuery不處理髮送數據
// 			contentType : 'multipart/form-data',(如果這樣,會導致contentType沒有邊界boundary,導致文件解析失敗,後臺報錯Could not parse multipart servlet request;)
            data: fd,
            success: function (res) {
                debugger
                if(res.code==0){
                    console.log(res.data[0].savePath+'上傳成功\n');
                }else{
                    console.error(filename+'上傳失敗\n');
                }
            },error:function(res){
                console.error(filename+'上傳失敗\n');
            }
        })


    }

    img.src="https://img.alicdn.com/imgextra/i4/6000000004742/O1CN0186kDCj1ktshI25kK9_!!6000000004742-0-try-report.jpg";

    function compress(img, width, height, ratio) {
        // img可以是dataURL或者圖片url
        /*	如果寬度大於 750 圖片太大 等比壓縮 	*/
        if(width > 750){
            var ratio = width/height;
            width = 750;
            height = 750/ratio;
        }
        var canvas, ctx, img64;
        canvas = document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;


        ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);
        /* canvas.toDataURL(mimeType(圖片的類型), qualityArgument(圖片質量)) */
        img64 = canvas.toDataURL("image/jpeg", ratio);

        return img64; // 壓縮後的base64串
    }
    //將base64轉換爲blob
    function dataURLtoBlob (dataurl) {
        var arr = dataurl.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 });
    }
    //將blob轉換爲file
    function blobToFile(theBlob, fileName){
        theBlob.lastModifiedDate = new Date();
        theBlob.name = fileName;
        return theBlob;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章