如何在手机做网站网站外链平台
后端返回一个文件链接的数组,前端处理下载逻辑,并且将这些文件存储在压缩包内部,这用的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);}
});