我正在使用Codeigniter。从ajax文件我调用下载控制器。我已经编写了我在网上找到的代码。但它没有开始下载文件。我创建了一个 onreadystatechangefunction(),其中我有一个div调用 myDiv 。
现在每当我点击下载按钮时,它只显示未开始下载的文件内容。 当我 onreadystatechangefunction() abort()时,我什么都没得到。 我只想在我点击下载按钮后立即开始下载未发生的文件。这是控制器代码:
PHP CONTROLLER
<?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
正在运作。
答案 0 :(得分:0)
答案 1 :(得分:0)
您可以在完成ajax调用后下载文件,然后重定向到文件路径。