createObjectURL 這個 API 好用的離譜,我舉幾個場景你們就懂了
隨著我用 URL.createObjectURL 這個 API 越來越多次,越發(fā)感覺真的是一個很好用的方法,列舉一下我在項(xiàng)目中用到它的場景吧!
圖片預(yù)覽
以前我們想要預(yù)覽圖片,只能是上傳圖片到后端后,獲取到url然后賦予給img標(biāo)簽,才能得到回顯預(yù)覽,但是有了URL.createObjectURL就不需要這么麻煩了,直接可以在前端就達(dá)到預(yù)覽的效果~
<body>
<input type="file" id="fileInput">
<img id="preview" src="" alt="Preview">
<script>
const fileInput = document.getElementById('fileInput');
fileInput.addEventListener('change', (event) => {
const file = event.target.files[0];
const fileUrl = URL.createObjectURL(file);
const previewElement = document.getElementById('preview');
previewElement.src = fileUrl;
});
</script>
</body>
音視頻流傳輸
舉個例子,我們通過MediaStream 去不斷推流,達(dá)到了視頻顯示的效果,有了URL.createObjectURL我們并不需要真的有一個url賦予video標(biāo)簽,去讓視頻顯示出來,只需要使用URL.createObjectURL去構(gòu)造一個臨時(shí)的url即可~非常方便~
<body>
<video id="videoElement" autoplay playsinline></video>
<script>
const videoElement = document.getElementById('videoElement');
navigator.mediaDevices.getUserMedia({ video: true, audio: true })
.then((stream) => {
videoElement.srcObject = stream;
})
.catch((error) => {
console.error('Error accessing webcam:', error);
});
</script>
</body>
結(jié)合 Blob
URL.createObjectURL結(jié)合Blob也可以做很多方便開發(fā)的事情~
WebWorker
我們知道,想要用 WebWorker 的話,是要先創(chuàng)建一個文件,然后在里面寫代碼,然后去與這個文件運(yùn)行的代碼進(jìn)行通信,有了URL.createObjectURL就不需要新建文件了,比如下面這個解決excel耗時(shí)過長的場景,可以看到,我們傳給WebWorker的不是一個真的文件路徑,而是一個臨時(shí)的路徑~
const handleImport = (ev: Event) => {
const file = (ev.target as HTMLInputElement).files![0];
const worker = new Worker(
URL.createObjectURL(
new Blob([
`
importScripts('https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.4/xlsx.full.min.js');
onmessage = function(e) {
const fileData = e.data;
const workbook = XLSX.read(fileData, { type: 'array' });
const sheetName = workbook.SheetNames[0];
const sheet = workbook.Sheets[sheetName];
const data = XLSX.utils.sheet_to_json(sheet, { header: 1 });
postMessage(data);
};
`,
]),
),
);
// 使用FileReader讀取文件內(nèi)容
const reader = new FileReader();
reader.onload = function (e: any) {
const data = new Uint8Array(e.target.result);
worker.postMessage(data);
};
// 讀取文件
reader.readAsArrayBuffer(file);
// 監(jiān)聽Web Worker返回的消息
worker.onmessage = function (e) {
console.log('解析完成', e.data);
worker.terminate(); // 當(dāng)任務(wù)完成后,終止Web Worker
};
};
下載文件
同樣也可以應(yīng)用在下載文件上,下載文件其實(shí)就是有一個url賦予到a標(biāo)簽上,然后點(diǎn)擊a標(biāo)簽就能下載了,我們也可以用URL.createObjectURL去生成一個臨時(shí)url
// 創(chuàng)建文件 Blob
const blob = new Blob([/* 文件數(shù)據(jù) */], { type: 'application/pdf' });
// 創(chuàng)建下載鏈接
const downloadUrl = URL.createObjectURL(blob);
const downloadLink = document.createElement('a');
downloadLink.href = downloadUrl;
downloadLink.download = 'document.pdf';
downloadLink.textContent = 'Download PDF';
document.body.appendChild(downloadLink);