Skip to content

Instantly share code, notes, and snippets.

@wewindy
Created May 24, 2021 01:49
Show Gist options
  • Save wewindy/013e14329e41646cd5796805e7c54735 to your computer and use it in GitHub Desktop.
Save wewindy/013e14329e41646cd5796805e7c54735 to your computer and use it in GitHub Desktop.
纯前端保存文件

使用a标签的 click 事件以及 URL.createObjectURL 方法 适合小文件的下载(无后端)

保存二进制文件

const buffer = new Float32Array([1, 2, 3, 4, 5]) // 创建一个类型数组,大小为 20 bytes
// 创建 blob 对象,第一个参数可以放置多个变量,这里放一个就好了
const blob = new Blob([buffer], {
  type: "application/octet-stream"
})
const a = document.createElement('a')
a.href = URL.createObjectURL(blob) // 用 blob 创建一个 url
a.setAttribute('download', '0.bin') // `0.bin` 是文件名,可替换为你需要的文件名(带后缀)
a.click() // 主动触发

保存文本类型文件(json为例)

const jsonStr = JSON.stringify({
  name: "Lily",
  gender: "female",
  age: 18
}, null, 2)
const blob = new Blob([jsonStr], {
  type: "application/json"
})
// 接下来如出一辙,仅在文件名处略有不同
const a = document.createElement('a')
a.href = URL.createObjectURL(blob)
a.setAttribute('download', 'demo.json')
a.click()
@wewindy
Copy link
Author

wewindy commented May 24, 2021

单次下载

如果对项目体积没什么需求的话,可以使用 file-saver 库进行下载。https://www.npmjs.com/package/file-saver

yarn add file-saver
yarn add @types/file-saver -D

示例

使用 Blob API

import { saveAs } from 'file-saver'
saveAs(new Blob([]), 'filename')

保存 canvas

import { saveAs } from 'file-saver'
const canvas = document.getElementById("my-canvas")
canvas.toBlob((blob) => {
  saveAs(blob, "pretty image.png")
})

直接保存地址资源

import { saveAs } from 'file-saver'
saveAs("https://httpbin.org/image", "image.jpg")

使用 FileAPI

// IE 和旧 edge 无 FileAPI 建议用 BlobAPI
import { saveAs } from 'file-saver'
const file = new File(["Hello, world!"], "hello world.txt", {type: "text/plain;charset=utf-8"})
saveAs(file)

流式下载

https://www.npmjs.com/package/streamsaver

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment