0

Changing the syntax within the first return of my fetch API call renders my zip file invalid. I have no idea why. After looking at Why does .json() return a promise? I modified my tentative code but to still no avail.

This works :

fetch("/photos/download_photos", {
    method: "POST",
    body: formData,
})
    .then(response => {
        return response.blob();
    })
    .then(response => {
        const blob = new Blob([response], {type: 'application/zip'});
        const downloadUrl = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = downloadUrl;
        a.download = "blah.zip";
        document.body.appendChild(a);
        a.click();
    });

This doesn't :

fetch("/photos/download_photos", {
    method: "POST",
    body: formData,
})
    .then(response => {
        response.blob().then((data) => {return {
            data: data,
            fileName: response.headers.get("content-disposition").split('; filename="')[1].slice(0, -1)}});
        };
    })
    .then((res) => {
        const blob = new Blob([res.data], {type: 'application/zip'});
        const downloadUrl = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = downloadUrl;
        a.download = res.fileName;
        document.body.appendChild(a);
        a.click();
    });

The only difference is I also access the headers property of the response to use it to name the file. Is there an interaction between response.headers and the blob() function that I am not aware of ? res in the second then is undefined in the second version of the code.

Chapo
  • 2,563
  • 3
  • 30
  • 60

0 Answers0