将 zip 文件从 reactjs 上传到 nodejs

IT技术 node.js reactjs express axios jszip
2021-05-14 17:18:12

我正在建立一个传输文件网站,但我正面临一个大问题!我正在与react.js express.js数字海洋空间合作。当我将文件拖到拖放区并点击提交时,文件应该上传到数字海洋空间,就像亚马逊 s3。所以,现在我可以毫无问题地上传文件,但是,如果我可以在通过 Express 将文件发送到数字海洋之前在 react 上压缩文件,那就更好了。这就是问题所在!我无法发送压缩文件!我已经用邮递员测试了 zip 文件的发送并且它可以工作,但是当我尝试使用 axios 从客户端(react)发送它时没有任何react。
请需要帮助:(我已经 3 天了,我一直在寻找如何使它工作但没有办法。非常感谢你们。

Upload.js 组件客户端(react):

export const upload = (form, callback = () => {}) => {

    const url = `${apiURL}/upload`;

    let files = _.get(form, 'files', []);

    let data = new FormData();

    const folderName = "upload";
    let zip = new JSZip();
    let content = zip.folder(folderName);

    _.each(files, (file) => {

        content.file(file);

    })            

    zip.generateAsync({type:"blob"}).then(function(blob) {           
        data.append('files', blob);
    });

    data.append('to', _.get(form, 'to'));
    data.append('from', _.get(form, 'from'));
    data.append('message', _.get(form, 'message'));

    const config = {

        onUploadProgress : (event) => {

            console.log('UPLOAD EVENT from Upload.js ', event);

            return callback({
                type : 'onUploadProgress',
                payload : event
            })
        }

    }

    axios.post(url, data, config).then((response) => {

        //upload success
        return callback({
            type : 'success',
            payload : response.data  
        })

    }).catch((err) => {
        return callback({
            type : 'error',
            payload : err
        })
    });
}
1个回答

最后我找到了解决方案,我的方法可能是正确的,但同时这个在前端使用 JSZIP 的解决方案被限制为 5Mo/文件,并且它的大小很差。因此,解决方案实际上是在服务器端(express)发送每个文件的相对路径并将其存储在 MONGODB 上。之后,在下载文件时,我使用文件存档器压缩从数字海洋收到的文件,将它们的相对路径直接放在 fileObject 的附加函数上。

这是代码:

类文件存档{

constructor(app, files = [], response) {

    this.app = app;
    this.files = files;
    this.response = response;

}

download(){

    const app = this.app;
    const files = this.files;
    const response = this.response;
    let fullPath = null;
    //const uploadDir = app.get('storageDirectory');
    const zip = archiver('zip');

    response.attachment('download.zip');
    zip.pipe(response);

    const s3Downloader = new S3Download(app, response);

    _.each(files, (file) => {

        fullPath = _.get(file, 'fullPath');
        const fileObject = s3Downloader.getObject(file);
        if(fullPath === null || fullPath === ''){
            zip.append(fileObject, {name : _.get(file, 'originalName')});
        } else {
            zip.append(fileObject, {name : _.get(file, 'fullPath')}); //Here put the absolute path (relative path)
        }


    })

    zip.finalize();

    return this;
}

}

//导出module module.exports = { FileArchiver }