1. 程式人生 > >JavaScript Base64 作為檔案上傳的例項程式碼解析

JavaScript Base64 作為檔案上傳的例項程式碼解析

這篇文章主要介紹了JavaScript Base64 作為檔案上傳的例項程式碼解析,非常不錯,具有參考借鑑價值,需要的朋友可以參考下。

例如我們用某些 裁剪外掛 得到的圖片是 :

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAkCAYAAABIdFAMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAHhJREFUeNo8zjsOxCAMBFB/ KEAUFFR0Cbng3nQPw68ArZdAlOZppPFIBhH5EAB8b+Tlt9MYQ6i1BuqFaq1CKSVcxZ2Acs6406KUgpt5/ LCKuVgz5BDCSb13ZO99ZOdcZGvt4mJjzMVKqcha68iIePB86GAiOv8CDADlIUQBs7MD3wAAAABJRU5ErkJggg==">

這樣的,那這樣的檔案怎樣在from 表單上傳(當然我是舉例,大部分的裁剪外掛都是有內建的)

首先需要把 base64 流轉換成 blob 物件,檔案物件都繼承它。

函式如下:

function getBlobBydataURI(dataURI,type) {  
  var binary = atob(dataURI.split(',')[1]);  
  var array = [];  
  for(var i = 0; i < binary.length; i++) {  
    array.push(binary.charCodeAt(i));  
  }  
  return new Blob([new Uint8Array(array)], {type:type });  
}

那麼剩下的就作為檔案上傳就ok

var $Blob= getBlobBydataURI(base64Data,'image/png');  
var formData = new FormData();  
formData.append("files", $Blob ,"file_"+Date.parse(new Date())+".png");

全部程式碼是這樣子的:

<!DOCTYPE html>  
<html>  
<head>  
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>  
  <title>上傳用例</title>  
  <meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>  
  <script type="text/javascript">  
    /**  
     * 根據base64 內容 取得 bolb  
     *  
     * @param dataURI  
     * @returns Blob  
     */ 
    function getBlobBydataURI(dataURI,type) {  
      var binary = atob(dataURI.split(',')[1]);  
      var array = [];  
      for(var i = 0; i < binary.length; i++) {  
        array.push(binary.charCodeAt(i));  
      }  
      return new Blob([new Uint8Array(array)], {type:type });  
    }  
    /**  
     * 上傳  
     */ 
    function upload(){  
      //base64 轉 blob  
      var $Blob= getBlobBydataURI(document.getElementsByTagName("img")[0].currentSrc,'image/jpeg');  
      var formData = new FormData();  
      formData.append("files", $Blob ,"file_"+Date.parse(new Date())+".jpeg");  
      //組建XMLHttpRequest 上傳檔案  
      var request = new XMLHttpRequest();  
      //上傳連線地址  
      request.open("POST", "www.xxx.com");  
      request.onreadystatechange=function()  
      {  
        if (request.readyState==4)  
        {  
          if(request.status==200){  
            console.log("上傳成功");  
          }else{  
            console.log("上傳失敗,檢查上傳地址是否正確");  
          }  
        }  
      }  
      request.send(formData);  
    }  
  </script>  
</head>  
<body>  
<button onclick="upload()">上傳測試</button>  
<br />  
上傳的圖片:  
<img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAeAB4AAD/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAEAAAAAAAD/2wBDABsSFBcUERsXFhceHBsgKEIrKCUlKFE6PTBCYFVlZF9VXVtqeJmBanGQc1tdhbWGkJ6jq62rZ4C8ybqmx5moq6T/wAALCABQADEBAREA/8QAGgAAAwADAQAAAAAAAAAAAAAAAwQFAAECBv/EADQQAAIBAwMCAgcGBwAAAAAAAAECAwAEEQUSITFBE1EVImFxgaHwBiMykbHRFEJDcoKiwf/aAAgBAQAAPwD0tc5AGc1MuftBYW7FfEMrDtGM/Ohp9pbNmUNHOgbo7qAP1p60vra8z4E6uR1HcfCmVrKHc3EdrBJNI2FUZNSIreXWR41w7xW38kSnBYebe/686o2ljaWwPgQxqemRyT8aO8UTqVeJWHkQKlzaHDuaS0Y28/VSh9X3EeX17KNpWoPc+Lb3KBLiDhwOhHmKo5qPqY9Iajb6eM+Go8aX2jsK71dmhW2tIcxrcSCNivUKeuKnw2mnyXc1rbJcRzxAnxd/UijwajdXkVlbrIqSXCsXkA5wCRx7eDQ7i4i024KxXV3PMuGKytlD8vLP5UfUHCXunaimVEuEYDqQeRVmpthg61qjHqPDH+p/anL+0F1Eu1gskbB42Izhh0pA2mqSho3a1h38PLGvrMK3Ppj24tpbHBktl2hWON47/Hmg3FnPduxbThbyyDa0xlDBR34HsouvRCLSIYlOdjoo+FP+tU6+b0Zq63pH3E6iOU4/Cex+VWI5FkUMrAg9CO9BvEnlgZLaURy54YjOKniy1sHPpKM/4D9qqqWCgOctgZ46mpN4w1HWLe1TlLY+LIfb2FWKHPBHcxtHKgZWGCCKi2y3FnqbWdlJ40CgM6yf0xnoD9frV+sqPrt1eWsG6EbIzgNL3XnsPr/tOaXZQWduFhbfv9ZnPVj503trrApeG0hgllkiTa0xzIck5P0TTGKzFDmhjnieKRdyOMMOmayGJIYkijXaqDCjOcCi1ql5ruGGQRt4hcjdhI2fj4A1w2oQqMsJ1Hm1vIB+eKJLdRQuElbYCMh24X3Z86WXWLJtv3yDchfl14x2PPWmra4juYEmiIKsM9c49nvo9aqXdyPHf+LGWXbHsObeSQdc8YwPnS5vnvrdgk6uN2DttJOx8wTinJ3dZFmhuCrSIQscqHacc5x1HGaQWYiaFI2UoYWCsLSX8ORwBu5B8/3qrpxJs4zuRlx6hQEAr24PNN1qlXhlnkKykCDPCLzv/uPl7Pn2ocVm8UZKSBJd7MGAyCCxIBHfrW/4eaa4Es2xQIigCknDE8noOwFci0mjeAwyIPCgMW5lJycr2yPI96ZtIBbWscAbdsUDPnR6/9k=" />  
</body>  
</html>

備註:

WindowOrWorkerGlobalScope.atob() 對用base-64編碼過的字串進行解碼 。你可以使用 window.btoa() 方法來編碼一個可能在傳輸過程中出現問題的資料,並且在接受資料之後,使用 atob() 方法再將資料解碼。例如:你可以編碼、傳輸和解碼操作各種字元,比如0-31的ASCII碼值。

let encodedData = window.btoa("Hello, world"); // 編碼
let decodedData = window.atob(encodedData); // 解碼

 


來源於:

https://www.jb51.net/article/105513.htm

https://developer.mozilla.org/zh-CN/docs/Web/API/WindowBase64/atob