1. JS Code
Ajax File Download
You can remove the data when you do not have to pass the parameter
jquery.download = function (URL, data, method) {//Get URL and data
if (URL && data) {
Data is a string or array/object
data = typeof data = = ' String '? Data:jQuery.param (data); To assemble parameters into a form input
var inputs = ';
Jquery.each (Data.split (' & '), function () {
var pair = this.split (' = ');
inputs+= ' <input type= "hidden" name= "' + pair[0] + '" value= "' + pair[1] + '"/> ';
}); Request to send requests
JQuery (' <form action= ' + URL + ' "method=" ' + (method| | ') Post ') + ' > ' +inputs+ ' </form> '). AppendTo (' body '). Submit (). remove ();
};
};
Invoke instance:
$.download (' exceldownload.do ',' Find=commoncode ',' post ');
2. PHP code
/**
* Download File
* @param string $file
* Path of the downloaded file
* @param string $name
* User sees the file name
*/
Public function Download () {
$file = "D:\\cloudwafsites.txt";
$name = ' Test ';
$fileName = $name? $name: PathInfo ($file, pathinfo_filename);
$filePath = Realpath ($file);
$fp = fopen ($filePath, ' RB ');
if (! $filePath | |! $fp) {
Header (' http/1.1 404 Not Found ');
echo "error:404 not Found. (Server file path error) ";
Exit
}
$fileName = $fileName. '. '. PathInfo ($filePath, pathinfo_extension);
$encoded _filename = UrlEncode ($fileName);
$encoded _filename = str_replace ("+", "%20", $encoded _filename);
Header (' http/1.1 OK ');
Header ("Pragma:public");
Header ("expires:0");
Header ("Content-type:application/octet-stream");
Header ("Content-length:". FileSize ($filePath));
Header ("Accept-ranges:bytes");
Header ("Accept-length:". FileSize ($filePath));
$ua = $_server["Http_user_agent"];
if (Preg_match ("/msie/", $ua)) {
Header (' content-disposition:attachment; filename= '. $encoded _filename. ‘"‘);
} else if (Preg_match ("/firefox/", $ua)) {
Header (' content-disposition:attachment; filename*= ' utf8\ ' \ '. $fileName. ‘"‘);
} else {
Header (' content-disposition:attachment; Filename= '. $fileName. ‘"‘);
}
Ob_end_clean (); <--some situations may need to call this function
Output file contents
Fpassthru ($FP);
Exit
}
Dynamic commit uses jquery to complete Ajax file downloads----back-end PHP