合网站建设,wordpress最好的博客主题,网站设计文献,企业网络营销的模式有哪些后端返回一个文件链接的数组#xff0c;前端处理下载逻辑#xff0c;并且将这些文件存储在压缩包内部#xff0c;这用的jszip 和 file-saver 这两个库。
步骤说明 1.使用 npm 或 yarn 安装 jszip 和 file-saver。 npm install jszip file-saver
2.获取文件内容#xff1a…后端返回一个文件链接的数组前端处理下载逻辑并且将这些文件存储在压缩包内部这用的jszip 和 file-saver 这两个库。
步骤说明 1.使用 npm 或 yarn 安装 jszip 和 file-saver。 npm install jszip file-saver
2.获取文件内容
使用 fetch API 获取每个文件的内容。 3.生成压缩文件
使用 jszip 将获取到的文件内容添加到压缩包中。4.下载压缩文件
使用 file-saver 将压缩包下载到客户端。
实例
import JSZip from jszip;
import { saveAs } from file-saver;async function fetchAndCompressFiles(fileUrls) {const zip new JSZip();// 并发请求文件内容const fileContents await Promise.all(fileUrls.map(async (url) {const response await fetch(url);if (!response.ok) {throw new Error(Failed to fetch ${url}: ${response.statusText});}return response.blob();}));// 添加文件到压缩包fileUrls.forEach((url, index) {const fileName url.substring(url.lastIndexOf(/) 1);zip.file(fileName, fileContents[index], { binary: true });});// 生成压缩包 Blobconst blob await zip.generateAsync({ type: blob });// 下载压缩包saveAs(blob, compressed-files.zip);
}// 示例文件 URL 数组
const fileUrls [http://example.com/file1.txt,http://example.com/file2.txt,http://example.com/file3.txt
];// 下载按钮的点击事件
document.getElementById(downloadButton).addEventListener(click, async () {try {await fetchAndCompressFiles(fileUrls);} catch (error) {console.error(Error compressing and downloading files:, error);}
});