How to implement jszip in react.js
Asked Answered
M

2

6

I am trying to zip a list of files before sending out through the http request. But I got stuck here.

export default function zipTargetFiles(files) {
    if (files.length <= 1) {
        return files;
    } else {
        const zip = require('jszip')();
        for (let i = 0; i < files.length; i++) {
            zip.file(files[i].name, files[i]);
    }
    return zip.generateAsync({type:"blob"});
}

}

Basically, the function takes in a list of files and tries to zip them into one single .zip file. But when i send it out as formed data, it gave the error that the submitted data was not a file.

I checked the payload in the header and the target field is as [object Promise]. How do I to truly return a .zip file?

Now I am able to catch the zip file in Redux-saga but it doesn't give an extension when I saved it in my database, instead it only give the name as 'blob'.

saga.js

const file = yield call(zipTargetFiles, files);
const formData = new FormData();
formData.append("coversheet", file);
const reponse = yield call(apiRequest, formData);
Mooned answered 18/10, 2018 at 21:15 Comment(0)
N
3

Whats happening is that .generateAsync is returning a promise. You will have to wait until the promise is either fulfilled or rejected before being able to work with the data.

Promises is a core concept in JS when working with async operations. You can read more about promises here

import zipTargetFiles from '/path'

zipTargetFiles( data ).then(file => {
 // Access your file here
})
Nevarez answered 18/10, 2018 at 21:42 Comment(1)
Got it! But how can I clarify the name of the file? Right now when I save it in my backend, it only appears as 'blob' without extension .zipMooned
P
4

To download and name the .zip folder you will need saveAs() from file-saver

import { saveAs } from "file-saver";

  zip
    .generateAsync({
      type: "blob"
    })
    .then(content => {
      saveAs(content, "fileName.zip");
    });
Posture answered 2/4, 2020 at 14:8 Comment(0)
N
3

Whats happening is that .generateAsync is returning a promise. You will have to wait until the promise is either fulfilled or rejected before being able to work with the data.

Promises is a core concept in JS when working with async operations. You can read more about promises here

import zipTargetFiles from '/path'

zipTargetFiles( data ).then(file => {
 // Access your file here
})
Nevarez answered 18/10, 2018 at 21:42 Comment(1)
Got it! But how can I clarify the name of the file? Right now when I save it in my backend, it only appears as 'blob' without extension .zipMooned

© 2022 - 2024 — McMap. All rights reserved.