<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="file">
<img src="" alt="">
<script>
document.getElementsByTagName('input')[0].onchange = function (event) {
let reader = new FileReader();
// file轉(zhuǎn)base64
reader.readAsDataURL(event.target.files[0]);
// file轉(zhuǎn)buffer文件, 注意如果要轉(zhuǎn)換blob文件的話最好先轉(zhuǎn)換為buffer再轉(zhuǎn)換為blob
// reader.readAsArrayBuffer(e.dataTransfer.files[0]);
reader.onload = function (base) {
// base64字符串編碼
console.log('base64:::', base.target.result);
// base64轉(zhuǎn)file
console.log('file', dataURLtoFile(base.target.result, event.target.files[0].name))
// base64轉(zhuǎn)blob
const blob = dataURLtoBlob(base.target.result);
console.log('blob', blob);
// blob本地使用路徑
const blobUrl = URL.createObjectURL(blob);
console.log('blob', blobUrl);
document.getElementsByTagName('img')[0].src = blobUrl;
// blob轉(zhuǎn)file
const files = new window.File(
[blob],
'圖片',
{ type: event.target.files[0].type }
);
console.log('file', files);
}
}
// base轉(zhuǎn)blob
function dataURLtoBlob(dataurl) {
var arr = dataurl.split(',');
//注意base64的最后面中括號(hào)和引號(hào)是不轉(zhuǎn)譯的
var _arr = arr[1].substring(0,arr[1].length-2);
var mime = arr[0].match(/:(.*?);/)[1],
bstr =atob(_arr),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime
});
}
//將base64轉(zhuǎn)換為文件
function dataURLtoFile(dataurl, filename) {
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 File([u8arr], filename, {
type: mime
});
}
</script>
</body>
</html>
文件轉(zhuǎn)換
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- ipynb文件如何轉(zhuǎn)換成.py文件并運(yùn)行? step1:pip install jupyter step2:在cm...
- 隨著辦公的越來(lái)越信息化,辦公軟件更新越來(lái)越多。辦公軟件的性能不同,也許在處理完后保存的文件格式都會(huì)不一樣,這樣在同...
- 在網(wǎng)上設(shè)計(jì)方面素材的時(shí)候,經(jīng)常看到很多制作好的圖紙,這種格式經(jīng)常出現(xiàn)在制圖或者工程上,那么我們想把這種格式轉(zhuǎn)換成J...
- NSString *path = [[NSBundle mainBundle]pathForResource:@"...
- 1. 文檔轉(zhuǎn)換 將 About.odt 轉(zhuǎn)成 About.docx (1) FileConverter/sourc...