I have an ajax call that saves some data to a database, but now I need to also download a zip file with a bunch of PDFs inside of it. My problem is that i can’t make it so the file I download isn’t corrupted. Can anyone spot if I am doing something wrong here? PHP version is 7.2.11 if that’s of any help.
Ajax code:
$.ajax({
url: "",
type:'POST',
data:{data: data},
xhrFields: {
responseType: 'blob'
},
success:function(result, status, xhr){
var blob = new Blob([result], { type: 'application/zip' });
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = 'cartas_convocacao.zip';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
},
});
Here is the PHP part of the code:
$zip = new ZipArchive();
$zipFile = 'cartas_convocacao.zip';
if ($zip->open($zipFile, ZipArchive::CREATE)) {
foreach ($chapas as $key => $value) {
if (strlen($chapas[$key]) > 0) {
//CODE TO CREATE PDF. SINCE IT IS ALSO CORRUPTED WITHOUT IT I DONT THINK THE PROBLEM IS HERE
}
}
$zip->close();
header('Content-Type: application/zip; charset=utf-8');
header('Content-Disposition: attachment; filename="cartas_convocacao.zip"');
header('Content-Length: ' . filesize($zipFile));
readfile(utf8_encode($zipFile));
}
exit();
Maybe what i am doing is not the best way of making this work. If so, could anyone give me an idea of a better way to implement this?