2
我想通過jQuery,AJAX和PHP發送文件到客戶端。我使用jQuery v1.11.2和XAMPP V3.2.1,用jQuery ajax和php發送文件到客戶端
這裏是我的jQuery代碼:
<script>
$(document).ready(function(){
$("#myBtn").click(function(){
$.ajax({ // post file name
type: "POST",
data: {
file: "testfile.xlsx"
},
url: "sendfile.php",
context: $("#result"),
success: function(data, status, xhr){
$(this).html(data);
}
});
});
});
</script>
sendfile.php:
<?php
FUNCTION send_file($name) { // function ... send file to client
OB_END_CLEAN();
$path = $name;
//cek connection if lost connection with client
IF (!IS_FILE($path) or CONNECTION_STATUS()!=0) RETURN(FALSE);
//header
//-------------------------------------------------------------
HEADER("Cache-Control: no-store, no-cache, must-revalidate");
HEADER("Cache-Control: post-check=0, pre-check=0", FALSE);
HEADER("Pragma: no-cache");
HEADER("Expires: ".GMDATE("D, d M Y H:i:s", MKTIME(DATE("H")+2, DATE("i"), DATE("s"), DATE("m"), DATE("d"), DATE("Y")))." GMT");
//set last modified property
HEADER("Last-Modified: ".GMDATE("D, d M Y H:i:s")." GMT");
HEADER("Content-Type: application/octet-stream");
HEADER("Content-Length: ".(string)(FILESIZE($path)));
HEADER("Content-Disposition: inline; filename=$name"); // file
HEADER("Content-Transfer-Encoding: binary\n");
//-----------------------------------------------------------------
IF ($file = FOPEN($path, 'rb')) { // send file
WHILE(!FEOF($file) and (CONNECTION_STATUS()==0)) {
PRINT(FREAD($file, 1024*8));
FLUSH();
}
FCLOSE($file);
}
RETURN((CONNECTION_STATUS()==0) and !CONNECTION_ABORTED());
}
// send file
if(!send_file($_POST['file'])){
echo "error.";
}
當我按下按鈕沒有文件接收而不是隨機語句#result
如果我直接在PHP函數中使用p roperly
send_file("testfile.xlsx");
有沒有更有效的方法?
類似的問題已經存在。這可能是你正在尋找的。 http://stackoverflow.com/questions/166221/how-can-i-upload-files-asynchronously – Sagar
您無法通過AJAX接收下載...您需要執行某種重定向。 –
我覺得這個鏈接會幫助你 http://stackoverflow.com/questions/5392344/sending-multipart-formdata-with-jquery-ajax –