先上代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>base64轉file</title>
</head>
<img class="img" id="img" width="200" height="200" src="234.png" alt="">
<canvas id="canvas" width="1000" height="1000"></canvas>
<body>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const img = document.getElementById('img');
// img加載完成
img.onload = function () {
ctx.drawImage(img, 10, 10)
}
// canvas轉base64
base64Data = canvas.toDataURL('image/jpg');
// base64轉blob
const base64ToBlob = function(base64Data) {
let arr = base64Data.split(','),
fileType = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
l = bstr.length,
u8Arr = new Uint8Array(l);
while (l--) {
u8Arr[l] = bstr.charCodeAt(l);
}
return new Blob([u8Arr], {
type: fileType
});
};
// blob轉file
const blobToFile = function(newBlob, fileName) {
newBlob.lastModifiedDate = new Date();
newBlob.name = fileName;
return newBlob;
};
// 調用
const blob = base64ToBlob(base64Data);
const file = blobToFile(blob, '123');
</script>
</body>
</html>
由於項目需要將base64轉換為file文件上傳到服務器 正常使用new File()就可以了 使用后發現ios系統有兼容問題 后來一頓搜索 找到了一個曲線救國的方法 就是 base64 ->blob->file 這樣就能解決ios的兼容問題了
atob(ascii to binary) 是window對象的函數,用於將ascii碼解析成binary數據。
Uint8Array 數組類型表示一個8位無符號整型數組,創建時內容被初始化為0。創建完后,可以以對象的方式或使用數組下標索引的方式引用數組中的元素。
