• createObjectURL的几个用途
  • 发布于 1个月前
  • 69 热度
    0 评论
  • CEBBCt
  • 4 粉丝 44 篇博客
  •   
前言
随着我用 URL.createObjectURL 这个 API 越来越多次,越发感觉真的是一个很好用的方法,列举一下我在项目中用到它的场景吧~

图片预览
以前我们想要预览图片,只能是上传图片到后端后,获取到url然后赋予给img标签,才能得到回显预览,但是有了URL.createObjectURL就不需要这么麻烦了,直接可以在前端就达到预览的效果~
<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 去不断推流,达到了视频显示的效果,有了URL.createObjectURL我们并不需要真的有一个url赋予video标签,去让视频显示出来,只需要使用URL.createObjectURL去构造一个临时的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>
结合 Blob
URL.createObjectURL结合Blob也可以做很多方便开发的事情~

WebWorker
我们知道,想要用 WebWorker 的话,是要先创建一个文件,然后在里面写代码,然后去与这个文件运行的代码进行通信,有了URL.createObjectURL就不需要新建文件了,比如下面这个解决excel耗时过长的场景,可以看到,我们传给WebWorker的不是一个真的文件路径,而是一个临时的路径~
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读取文件内容
  const reader = new FileReader();

  reader.onload = function (e: any) {
    const data = new Uint8Array(e.target.result);
    worker.postMessage(data);
  };
  // 堆代码 duidaima.com
  // 读取文件
  reader.readAsArrayBuffer(file);

  // 监听Web Worker返回的消息
  worker.onmessage = function (e) {
    console.log('解析完成', e.data);
    worker.terminate(); // 当任务完成后,终止Web Worker
  };
};
下载文件
同样也可以应用在下载文件上,下载文件其实就是有一个url赋予到a标签上,然后点击a标签就能下载了,我们也可以用URL.createObjectURL去生成一个临时url
// 创建文件 Blob
const blob = new Blob([/* 文件数据 */], { type: 'application/pdf' });

// 创建下载链接
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);

用户评论