@sunzan/universal-file-dl
v0.1.0
Published
通用文件流导出工具:自动解析文件名,兼容 fetch/axios,支持任意格式
Downloads
0
Maintainers
Readme
文件流导出工具
通用浏览器端下载工具,兼容任意格式(以服务端返回为准),支持:
- 自动解析
Content-Disposition得到文件名(兼容filename*UTF-8 与filename) - 适配
fetch与axios响应对象 - 直接传入
Blob/ArrayBuffer/Uint8Array下载
安装/放置
可以直接复制 src/utils/fileDownload.js,或通过 npm 安装:
npm i universal-file-download
# 或
pnpm add universal-file-download使用:
import downloader, { downloadByFetch, downloadFromAxiosResponse } from 'universal-file-download';API
resolveFilename(headers, fallback?, url?):从响应头/URL 推断文件名downloadFromFetchResponse(response, { filename? }):基于 fetchResponse下载downloadFromAxiosResponse(axiosResponse, { filename? }):基于 axios 响应下载(需设置responseType)downloadByFetch(url, fetchInit?):直接传入 URL,用 fetch 请求并下载downloadFromData(data, { filename, type? }):从原始数据(Blob/ArrayBuffer/Uint8Array)下载
用法示例
1) 使用 axios
import axios from 'axios';
import downloader from './src/utils/fileDownload';
async function exportWithAxios() {
const res = await axios.get('/api/export', {
responseType: 'blob', // 或 'arraybuffer'
params: { q: 'keyword' },
});
await downloader.downloadFromAxiosResponse(res, { filename: 'fallback.xlsx' });
}2) 使用 fetch(已拿到 Response)
import { downloadFromFetchResponse } from './src/utils/fileDownload';
async function exportWithFetchResponse() {
const res = await fetch('/api/export', { credentials: 'include' });
await downloadFromFetchResponse(res, { filename: 'fallback.csv' });
}3) 使用 fetch 直接请求并下载
import { downloadByFetch } from './src/utils/fileDownload';
async function exportByUrl() {
await downloadByFetch('/api/export?type=zip', { filename: 'fallback.zip' });
}4) 从原始数据下载
import { downloadFromData } from './src/utils/fileDownload';
async function exportFromData() {
const data = new Uint8Array([1,2,3,4]);
downloadFromData(data, { filename: 'demo.bin', type: 'application/octet-stream' });
}服务器返回建议
- 设置正确的
Content-Type,例如application/vnd.openxmlformats-officedocument.spreadsheetml.sheet等 - 设置
Content-Disposition:attachment; filename="report.xlsx"- 或
attachment; filename*=UTF-8''%E6%8A%A5%E8%A1%A8.xlsx
注意事项
- Safari/部分浏览器需要使用 Blob URL 触发下载,工具已处理
- 若服务端返回 JSON 错误体而非二进制,请在触发下载前根据项目约定先判断响应是否为文件(例如检查
content-type是否包含application/json),再做错误处理
演示页运行
无需构建工具,直接本地打开 demo 页面:
- 用本机静态服务器(推荐)
npx http-server . -p 8080
# 或者:python3 -m http.server 8080浏览器访问 http://localhost:8080/demo/,点击三个按钮进行测试。
- 直接 file:// 打开
双击打开 demo/index.html 也可运行,但某些浏览器对 module + 相对路径在 file:// 下有安全限制,建议使用本机静态服务器。
