React中返回JSZip zip文件

问题描述 投票:0回答:1

我有一个压缩文件的功能,但是atm它会返回一个promise。我尝试实现此方法:jszip stackoverflow,但仍返回未解决的承诺。

我不太了解Promise,也完全不熟悉jsZIP-如何获得此函数以返回压缩文件?

const getZip = (url) => {
        setLoadingStatus('zipping...')
        let zip = new JSZip();
        console.log("TYPOF URL", url, typeof url)
        zip.file("Report", url)
        var promise = null;
        if (JSZip.support.uint8array) {
        promise = zip.generateAsync({type : "uint8array"}).then(content => {
            saveAs(content, "Report.zip");
          });
        } else {
        promise = zip.generateAsync({type : "string"}).then(content => {
            saveAs(content, "Report.zip");
          });
        }
        console.log("TYPEOF PROMISE", promise, typeof promise) //typeof is always promise
        return promise
    }

异步等待:

    async function getZip(url){
    setLoadingStatus('zipping...')
    let zip = new JSZip();
    console.log("TYPOF URL", url, typeof url)
    zip.file("Report", url)
    var content = null;
    if (JSZip.support.uint8array) {
        content = await zip.generateAsync({type : "uint8array"}).then(content => {
            saveAs(content, "Report.zip");
          })
    } else {
        content = await zip.generateAsync({type : "string"}).then(content => {
            saveAs(content, "Report.zip");
          })
    }
    return content
}

调用getZip()的函数是:

const createURL = useCallback((node, reportHeight, reportWidth, imgHeight) => {

        domtoimage.toJpeg(node, {width: reportInViewerRef.current.offsetWidth, height: reportInViewerRef.current.scrollHeight})
    .then(function (dataUrl) {
        const pdf = new jsPDF('p', 'px', [reportWidth, imgHeight]);
        setLoadingStatus('pdf created')
        pdf.addImage(dataUrl, 'JPEG', 0, -12, reportWidth, reportHeight );
        setLoadingStatus('image added')
        let fileName = getUniqueFilename()
        let base64pdf = getZip(btoa(fileName, pdf.output()));
        console.log("ZIP FILE =================", base64pdf)
        let storageRef = firebase.storage().ref();
        setLoadingStatus('uploading...')
        let fileLocation = '/pdfs/' + fileName + '.zip'
        let reportPdfRef = storageRef.child(fileLocation);
        reportPdfRef.putString(base64pdf, 'base64').then(function() {
            console.log('Uploaded a data_url string!', reportPdfRef,
            reportPdfRef.getDownloadURL().then(function(url) {
                setLoadingStatus('linking...')
                setTemplateParams({
                    to: sessionData.customerEmail,
                    customers: name, 
                    adviser: adviserFullName,
                    adviserEmail: adviserEmail,
                    adviserAvatar: adviserAvatar,
                    content: url

                }) 
                firebase
                .firestore()
                .collection('sessions')
                .doc(sessionData.id)
                .update({
                    'pdfDownloadURL': url
                }).then(function() {
                    setLoadingStatus('sending email')
                    setSendingEmail(false);
                  });
              }).catch(function(error) {
                switch (error.code) {
                  case 'storage/object-not-found':
                        console.log("FILE DOES NOT EXIST")
                    break;
                  case 'storage/unauthorized':
                        console.log("USER DOES NOT HAVE PERMISSION TO ACCESS THIS FILE")
                    break;

                  case 'storage/canceled':
                        console.log("USER CANCELLED THE UPLOAD")
                    break;
                  case 'storage/unknown':
                        console.log("SERVER ERROR")
                    break;
                }
              })
            )
          });
        })
        .catch(function (error) {
            console.error('oops, something went wrong!', error);
        });
}, [])
reactjs es6-promise jszip
1个回答
0
投票

由于zip创建是异步的,因此处理它的代码也需要异步。做你的createURL处理程序异步和await内部的zip:

const createURL = useCallback(async (node, reportHeight, reportWidth, imgHeight) => {
    // ...

    let base64pdf = await getZip(btoa(fileName, pdf.output()));

    // ... do something with the zip file
}
© www.soinside.com 2019 - 2024. All rights reserved.