php通过ajax下载文件,请教通过ajax调用php下载文件

我遇到了一个稍微困难的问题:1.发送带有POST数据的Ajax请求,让服务器生成一个ZIP文件;2.获得响应;3.下载ZIP文件

所以我就是这样做的(使用JQuery来处理Ajax请求):初步员额请求:var parameters = {

pid     : "mypid",

"files[]": ["file1.jpg","file2.jpg","file3.jpg"]}

var options = {

url: "request/url",//replace with your request url

type: "POST",//replace with your request type

data: parameters,//see above

context: document.body,//replace with your contex

success: function(data){

if (data) {

if (data.path) {

//Create an hidden iframe, with the 'src' attribute set to the created ZIP file.

var dlif = $('',{'src':data.path}).hide();

//Append the iFrame to the context

this.append(dlif);

} else if (data.error) {

alert(data.error);

} else {

alert('Something went wrong');

}

}}};$.ajax(options);

“requesturl”处理zip创建(OFF主题,所以我不会发布完整的代码)并返回以下JSON对象。类似于://Code to create the zip file

//......

//Id of the file

$zipid = "myzipfile.zip"

//Download Link - it can be prettier

$dlink = 'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid;

//JSON response to be handled on the client side

$result = '{"success":1,"path":"'.$dlink.'","error":null}';

header('Content-type: application/json;');

echo $result;

如果需要,“请求/下载”可以执行一些安全检查,并生成文件传输:$fn = $_GET['file'];if ($fn) {

//Perform security checks

//.....check user session/role/whatever

$result = $_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn;

if (file_exists($result)) {

header('Content-Description: File Transfer');

header('Content-Type: application/force-download');

header('Content-Disposition: attachment; filename='.basename($result));

header('Content-Transfer-Encoding: binary');

header('Expires: 0');

header('Cache-Control: must-revalidate, post-check=0, pre-check=0');

header('Pragma: public');

header('Content-Length: ' . filesize($result));

ob_clean();

flush();

readfile($result);

@unlink($result);

}}