-1

I am working on a code to compress files using PHP and download the zip, How do I initiate the download using jQuery?

When I reload the PHP script through the browser, the file is downloaded normally as zip, but when I send a request from jQuery, the file is returned from the server as gibberish characters when I visualize in the browser console. Please not I can automatically download a file using php, but the problem is when I try to use jQuery to fetch the zip file

The php code in the file file.php

$file_path = '/path/tofile/file.php'
$file_name  = basename($file_path);
header('Content-Type: application/zip');
header("Content-Transfer-Encoding: Binary");
header('Content-Disposition: attachment; filename="'.$file_name.'"');
header("Content-Length: ".filesize($file_path));

flush();
readfile($file_path);

The corresponding ajax request

$.get('file.php',  function(data)
{
}
);

I expect the file to be downloaded as a normal zip file from jQuery but instead gibberish characters are sent to the browser

daRula
  • 143
  • 2
  • 12
  • Possible duplicate of [How to force file download with PHP](https://stackoverflow.com/questions/7263923/how-to-force-file-download-with-php) – miken32 Apr 28 '19 at 20:58
  • Its not a duplicate, the problem is more on the jQuery side – daRula Apr 30 '19 at 19:05

1 Answers1

0

I managed to solve the problem by the solution provided https://stackoverflow.com/a/42830315/6245812

let urlToSend = "file.php";
let req = new XMLHttpRequest();
let formdata = new FormData();
formdata.append("user", "joe");
formdata.append("id", "10");

req.addEventListener("load", function (event) {
   console.log(req.response);
   let blob = req.response;
   let fileName = req.getResponseHeader("fileName"); //if you have the fileName header available
   let link=document.createElement('a');
   link.href=window.URL.createObjectURL(blob);
   link.download=fileName;
   link.click();
}, false);

req.open("POST", urlToSend, true);
req.responseType = "blob";
req.send(formdata);

I only changed the request type from GET to POST as GET was not allowing me to send parameters.

daRula
  • 143
  • 2
  • 12