我曾经遇到这个问题,但最终解决了,并希望在今后有人遇到同样问题时分享我的经验。
该函数用作站点上按钮的 onClick,当单击按钮时,它需要从各个远程 URL(一个CMS)抓取所有对应的 .zip
文件并捆绑成一个单独的 .zip
,然后下载给用户。
请参阅下面的答案获取代码。
import JSZip from 'jszip';
import { saveAs } from 'file-saver';
//.... some react component
const handleZipDownload = async () => {
var zip = new JSZip();
// block.packages is an array of items from the CMS
const remoteZips = block.packages.map(async (pack) => {
// pack.file.url is the URL for the .zip hosted on the CMS
const response = await fetch(pack.file.url);
const data = await response.blob();
// pack.kitName is from a loop, replace with your file name.
zip.file(`${pack.kitName}.zip`, data);
return data;
})
Promise.all(remoteZips).then(() => {
zip.generateAsync({ type: "blob" }).then((content) => {
saveAs(content, `your-pack-name.zip`);
})
})
}
//... rest of component + JSX