菜鸟-创作你的创作

JavaScript中URL.createObjectURL和Blob实现保存文件

下面给你一份 前端实战级、可复制即可用的

《JavaScript 中 URL.createObjectURL + Blob 实现保存文件(超详细教程)》

涵盖:


✅ 一、核心概念:Blob 与 createObjectURL


1. Blob 是什么?

Blob(Binary Large Object)表示 二进制数据块,常用于:

简单理解:

👉 Blob = 前端构造的“文件”

创建方式:

const blob = new Blob(["hello world"], { type: "text/plain" });


2. URL.createObjectURL() 是什么?

它用于为 BlobFile 创建一个 临时 URL

const url = URL.createObjectURL(blob);

生成的 URL 类似:

blob:https://xxx.com/df7a9sdf-9234...

这种 URL 可以:

并且无需上传到服务器。


🚀 二、使用 Blob + createObjectURL 下载文件(通用模板)

这是你前端下载文件最常用的代码,直接可用:

function downloadBlob(blob, filename) {
  const url = URL.createObjectURL(blob);

  const a = document.createElement("a");
  a.href = url;
  a.download = filename;

  // 触发下载
  a.click();

  // 释放 URL
  URL.revokeObjectURL(url);
}


⭐ 三、下载不同类型文件的实战示例


① 下载 TXT 文本文件

const blob = new Blob(["这是一个文本文件"], {
  type: "text/plain;charset=utf-8"
});

downloadBlob(blob, "test.txt");


② 下载 JSON 文件

const data = { name: "阿杰", age: 20 };

const blob = new Blob([JSON.stringify(data, null, 2)], {
  type: "application/json"
});

downloadBlob(blob, "data.json");


③ 下载图片(将 base64 转换为 Blob)

function base64ToBlob(base64, contentType = "image/png") {
  const byteString = atob(base64.split(",")[1]);
  const buffer = new ArrayBuffer(byteString.length);
  const uint8 = new Uint8Array(buffer);

  for (let i = 0; i < byteString.length; i++) {
    uint8[i] = byteString.charCodeAt(i);
  }

  return new Blob([buffer], { type: contentType });
}

const blob = base64ToBlob(base64String);
downloadBlob(blob, "image.png");


④ 下载后端返回的文件流(arraybuffer)

fetch("/api/download")
  .then(res => res.arrayBuffer())
  .then(buffer => {
    const blob = new Blob([buffer], {
      type: "application/octet-stream"
    });
    downloadBlob(blob, "file.zip");
  });


⑤ 下载 CSV 文件

const csvContent = "name,age\n阿杰,18\n小王,20";

const blob = new Blob([csvContent], {
  type: "text/csv;charset=utf-8;"
});

downloadBlob(blob, "users.csv");


⑥ 使用 createObjectURL 显示图片(非下载)

const blob = new Blob([file], { type: file.type });
const url = URL.createObjectURL(blob);

document.getElementById("preview").src = url;


🧨 四、关于 URL.revokeObjectURL() 的重要说明

一定要记得释放!

URL.revokeObjectURL(url);

否则可能导致:

浏览器不会自动回收这些 URL。


🛠 五、封装一个万能“前端保存文件”工具(可放入 utils)

export function saveFile(content, filename, mimeType) {
  const blob = new Blob([content], { type: mimeType });
  const url = URL.createObjectURL(blob);

  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  a.style.display = "none";

  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);

  URL.revokeObjectURL(url);
}

使用:

saveFile("hello world", "hello.txt", "text/plain");


📌 六、Vue 中如何使用?

<script setup>
import { saveFile } from "@/utils/saveFile.js";

const download = () => {
  saveFile("Vue 3 很好用!", "vue.txt", "text/plain");
};
</script>

<template>
  <button @click="download">下载文件</button>
</template>


🎯 七、终极总结(背下来就会用)

API作用
Blob前端生成文件
URL.createObjectURL生成临时文件 URL
a.download浏览器触发下载
URL.revokeObjectURL释放内存
退出移动版