我正在使用 Codeigniter。从一个 ajax 文件中,我调用了一个下载控制器。我已经编写了我在网上找到的代码。但它没有开始下载文件。我创建了一个onreadystatechangefunction()我有一个 div 调用myDiv。
现在,每当我单击下载按钮时,它只显示未开始下载的文件内容。当我可以在onreadystatechangefunction()中abort()时,我什么也没得到。我只想在单击下载按钮后立即开始下载未发生的文件。这是控制器代码:
PHP 控制器
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class Downloadfilefromserver extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('security');
$this->load->library('tank_auth');
$this->load->helper('file');
$this->load->helper('download');
}
function index()
{
echo "welcome to downlaod a course index";
}
function pushFileFromServer()
{
$path = $this->input->post('dl_file_path');
$file_name_in_server_arr = preg_split("/\\/uploads\\//", $path ); //also can be get by basename($path)
$name= ($file_name_in_server_arr[1]);
// make sure it's a file before doing anything!
if(is_file($path)){
// required for IE
if(ini_get('zlib.output_compression')){
ini_set('zlib.output_compression', 'off');
}
// get the file mime type using the file extension
$mime = get_mime_by_extension($path);
// Build the headers to push out the file properly.
header('Pragma: public'); // required
header('Expires: 0'); // no cache
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Last-Modified: '.gmdate ('D, d M Y H:i:s', filemtime ($path)).' GMT');
header('Cache-Control: private',false);
header('Content-Type: '.$mime); // Add the mime type from Code igniter.
header('Content-Disposition: attachment; filename="'.basename($path).'"'); // Add the file name
header('Content-Transfer-Encoding: binary');
header('Content-Length: '.filesize($path)); // provide file size
header('Connection: close');
readfile($path); // push it out
//$data = file_get_contents($path); // Read the file's contents
//force_download($name, $data);
exit();
}
}
}
Javascript
这是我从中调用控制器的ajax代码:
function downloadUploadedFile(dl_file_path,dl_file_name){
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
abort();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","../downloadfilefromserver/pushFileFromServer",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("dl_file_path="+dl_file_path+"&dl_file_name="+dl_file_name);
}
我想补充一点
xmlhttp.readyState==4 && xmlhttp.status==200
正在工作中。