I am trying to implement the download of a ZIP archive from server using Next.js, axios and js-file-download. However, when I try to open the downloaded archive, an error pops up saying that the archive is corrupted.
I am positive that the archive on the server is valid, so the problem is in the transfer to the client.
Also, if I try to download another file type (for example a .txt file), it works.
This is the server code, in /pages/api/assignments/[assignmentId]/students/index.tsx:
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const assignmentId = req.query.assignmentId as string;
const assignment = // here I get assignment from database
switch(req.method) {
case('GET'):
const fileNames = assignment.fileUploads.map((fileUpload: AssignmentFileUpload) => fileUpload.fileName);
const archivePath = `./resources/assignment_archives/${assignmentId}.zip`;
// --- RELEVANT CODE STARTS HERE ---
const archiveReadStream = fs.createReadStream(archivePath);
res.writeHead(200, {
'Content-Type': 'application/zip',
'Content-Disposition': `attachment; filename=${assignment.title}.zip`
});
archiveReadStream.pipe(res);
}
}
And this is the code on the client side:
const handleDownload = async (event: any) => {
axios.get(`/api/assignments/${assignment.id}/students`, {
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/zip'
}
})
.then((res) => {
fileDownload(res.data, `${assignment.title}.zip`) // function imported from js-file-download
});
}
I have already tried fiddling with headers, but nothing worked.