生成多个文档并压缩以供下载



我目前在我的react应用程序中使用docx.js,我已经设置了AWS Amplify(节点后端)。我正在生成多个文档,并使用打包器单独保存它们以生成文档作为blob,然后使用filesver .js的saveAs函数下载。参见下面的代码示例:

const aDoc = new Document();
const bDoc = new Document();
const cDoc = new Document();
// Code that adds content to each doc
// Use packer to generate document as blob and download using FileSaver
Packer.toBlob(aDoc).then((blob) => {
// saveAs from FileSaver will download the file
FileSaver(blob, "aDoc.docx");
});
Packer.toBlob(bDoc).then((blob) => {
// saveAs from FileSaver will download the file
FileSaver(blob, "bDoc.docx");
});
Packer.toBlob(cDoc).then((blob) => {
// saveAs from FileSaver will download the file
FileSaver(blob, "cDoc.docx");
});

现在我在想,我怎么能把这些都放到一个ZIP文件中,让用户下载呢?我还没有真正找到很多,只是这个,这似乎更像是一个解决方案,因为它使用timeout来避免有许多文档时的问题——我宁愿避免这种情况,而把它下载到存档中。我看过一些库,比如上面提到的JSZip,但是我真的不明白如何把docx.js给我的东西放到归档文件中。

看看如何使用JSZip - https://www.npmjs.com/package/jszip

我已经重新编写了一些我在POC中使用的代码,我相信它可以与您的项目和上面的代码一起工作。

var JSZip = require('jszip')
const Demo = () => {
const demoClick = () => {
var zip = new JSZip()
const zipFilename = 'test.zip'
const blobs = []
Packer.toBlob(aDoc).then((blob) => {
blobs.push(blob)
})
// repeat if needed
var urlArr = blobs // this will be your set of blobs you are downloading on their own right now.
urlArr.forEach(function (url) {
var filename = 'test.docx'
zip.file(filename, url, { binary: true })
})
zip.generateAsync({ type: 'blob' }).then(function (content) {
// you may need to work the content into a zip blob like this depending how FileSaver takes it
const zipContents = URL.createObjectURL(content)
//or
const zipContents = new Blob([content], {
type: 'application/zip'
})
// saveAs from FileSaver will download the file
FileSaver(content, zipFilename)
})
}
return <button onClick={demoClick}>demo</button>
}

如果FileSaver不喜欢ZIP的格式,那么你可以使用更简单的非导入下载/保存方法

const zipContents = URL.createObjectURL(content)
if (window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(content, zipFilename)
} else if (isIOS && isChrome) {
window.open(zipContents, '_blank')
} else {
const link = document.createElement('a')
link.href = zipContents
link.target = '_blank'
link.download = zipFilename
link.click()
}

最新更新