示例
javascript
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>js的File对象,Blob和file相互转换</title>
<style>
.prview {
display: flex;
margin: 10px;
}
.prview .rename {
display: inline-block;
width: 60px;
}
.prview img {
width: 200px;
height: 200px;
}
</style>
</head>
<body>
<input type="file" onchange="upload(this)" />
<div class="prview">
<span class="rename">base64:</span>
<img id="base64" src="" alt="" />
</div>
<div class="prview">
<span class="rename">blob:</span>
<img id="blob" src="" alt="" />
</div>
<script>
const upload = async (e) => {
let files = e.files[0];
console.log(files);
// file转base64
let base64 = await fileToBase64(files);
setImage('base64', base64) //设置图片
// base64转blob
let blob = parseBlob(base64);
setImage('blob', blob) //设置图片
// blob转file
let file = blobToFile(blob);
console.log(file);
};
// blob转file
const blobToFile = (blob) => {
let rename = new Date().getTime() + ".png";
let file = new File([blob], rename, { type: "image/png" });
return file;
};
// base64转blob
const parseBlob = (base64) => {
var arr = base64.split(",");
var mime = arr[0].match(/:(.*?);/)[1];
var bstr = atob(arr[1]);
var n = bstr.length;
var u8arr = new Uint8Array(n);
for (var i = 0; i < n; i++) {
u8arr[i] = bstr.charCodeAt(i);
}
var url = URL || webkitURL;
return url.createObjectURL(new Blob([u8arr], { type: mime }));
};
// file转base64
const fileToBase64 = (file) => {
return new Promise(function (resolve, reject) {
const reader = new FileReader();
let imgResult = "";
reader.readAsDataURL(file);
reader.onload = function () {
imgResult = reader.result;
};
reader.onerror = function (error) {
reject(error);
};
reader.onloadend = function () {
resolve(imgResult);
};
});
};
// 设置格式到图片
const setImage = (id, val) => {
let img = document.getElementById(id)
img.setAttribute('src', val)
}
</script>
</body>
</html>