My app has the ability to request and download a multitude of different files and types from the database.
The way I'm currently doing this is with a hidden form input that will submit the request to server which then does the processing and downloads the file. The code for that looks like this:
var action = '/download/downloader.php?actionname&filename=' + downloadfilename;
var A = document.createElement("div");
A.style.display = "none";
document.body.appendChild(A);
var formKey = 'someid';
A.innerHTML = '<form id="' + formKey + '" method="post" action="' + action + '" accept-charset="utf-8" enctype="application/x-www-form-urlencoded"' + target + '><input type="hidden" name="segmentno" id="segmentno"/> </form>';
document.getElementById(formKey).submit();
A.parentNode.removeChild(A);
The PHP side for downloading an XML file will look something like this (all the cases set the output data and headers accordingly)
// $a is the data from the database
$xmlEncode = new XMLEncode();
$xmlstring = $xmlEncode->XML_SerializeData($a);
$xmlstring = str_replace(''', '''', $xmlstring);
header("Content-type: application/xml; charset=UTF-8");
header("Content-Disposition: attachment;filename=". $this->sFileName .".xml");
header("Cache-Control: max-age=0");
exit($xmlstring);
This works great when there is no pre-processing required (permission checks, valid key checks, etc...)
However, if I have some server-side pre-processing to do prior to this portion, and it fails, I need a way to send a message back to the front end.
I know with what I have, it will not work. My only thought is that I will need to do the pre-processing in a separate AJAX call and then if it's successful, run the actual download but that isn't ideal. Some other solutions I've looked into include using fetch to get the data back and then potentially using a library to download the blob data but again, I'm not sure if I can tell whether or not it was actually a successful server request or not.
Thanks in advance.
What I ended up doing is creating an iFrame for the download and the form will target it.
Now my download class will return an output array to the download endpoint where I can check if it passed the pre process, process, and post processing. If it did not succeed, I set the headers to back to text/html and inject a line of JS into the iFrame window where I can then target the parent window and call my error function with the message passed from the output data.
My PHP download endpoint:
if (!$aOutput['success']){
header("Content-type: text/html; charset=UTF-8");
header("Content-Disposition: inline");
exit('<script type="text/javascript">if (window.parent.Footer) {window.parent.Footer._download.error(\''. $aOutput['data'] .'\') } else { window.parent.w360.error(\'' . $aOutput['data'] . '\', \'Download Failed\')}</script>');
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments