javascript - Why can't I download zip-file in my php model if acces it from ajax script. Works fine from php link -
i have links number of images (my object contains links). want download these images in zip file. started code works well.
download link in view (to controller)
<a href="<?php echo url . 'album/downloadimage/' ?>" id="disablebutton" class="download-button"><span class="glyphicon glyphicon-download" aria-hidden="true"></span></span>download photos</a>
my controller
public function downloadimage() { $this->model->downloadimage(); }
and model. model automatically start downloading zip file containing images
public function downloadimage() { $imagenumber = 1; $zipname = 'name-'.date("y-m-d").'.zip'; # create new zip opbject $zip = new ziparchive(); # create temp file & open $tmp_file = tempnam('.',''); $zip->open($tmp_file, ziparchive::create); # loop through each file foreach($this->imageurl $file){ # extension $ext = pathinfo(parse_url($file->url, php_url_path), pathinfo_extension); # download file $download_file = file_get_contents($file->url); # add zip $zip->addfromstring(basename($imagenumber.'-name.'.$ext),$download_file); $imagenumber++; } # close zip $zip->close(); # send file browser download header('content-type: application/zip'); header('content-disposition: attachment; filename='.$zipname); header('content-length: ' . filesize($tmp_file)); readfile($tmp_file);
}
this code works fine because want modify html tags during , after download want make call through ajax instead.
updated view link to
<a href="#" id="disablebutton" class="download-button"><span class="glyphicon glyphicon-download" aria-hidden="true"></span></span>download photos</a>
and added .js-file
if ($('#disablebutton').length !== 0) { $('#disablebutton').on('click', function() { $.ajax(url + "album/downloadimage") .done(function(result) { //done }) .fail(function() { // executed if ajax-call had failed }) .always(function() { // executed, regardless if ajax-call success or not }); }); }
all other code same. have tested log in controller , model function , access them download not start.
why not download of zip file start if call through ajax function works if make through php in html link. receive no error message.
use jquery file download plugin this. it's simple:
$.filedownload('some/file.pdf') .done(function () { alert('file download success!'); }) .fail(function () { alert('file download failed!'); });
Comments
Post a Comment