[英]download an existing file using codeigniter
我正在嘗試制作一個網站,可以下載由管理員上傳的jpg,png,pdf,docx文件。
上傳這些內容沒有問題。 上傳時,我也將該文件名插入到mysql表中。 使用該表,我向用戶顯示上傳的文件名。
這是我用來顯示這些文件的代碼。
<?php
if (!empty($downloads)) {
foreach ($downloads as $val) {
?> <div class="col-md-3 col-sm-6 col-xs-12">
<div class="panel panel-danger">
<div class="panel-heading panel-title">
<?php echo $val['upload_description']; ?>
</div>
<div class="panel-body">
<?php echo $val['file_name']; ?>
<div class="clear-fix clear clearfix"></div>
<div id="download" onclick="downloadFile('<?php echo $val['file_name']; ?>');" class="btn btn-danger">Download</div>
</div>
</div>
</div>
<?php
}
}
?>
這是我的ajax代碼
function downloadFile(str) {
//alert(str);
$.ajax({
type: 'POST',
url: 'downloadfiles',
data: {value: str},
success: function(data) {
alert('ok' + data);
}
});
}
當有人單擊下載按鈕時,使用ajax和jquery將文件名發送到download_controller。 這是download_controller文件中的功能
public function download_files() {
$fileName = $this->input->post('value');
$file_path = 'uploaded/' . $fileName;
$this->_push_file($file_path, $fileName);
}
function _push_file($path, $name) {
$this->load->helper('download');
// 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
$this->load->helper('file');
$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($name) . '"'); // 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
exit();
}
}
但是下載從未開始。 當嘗試下載png文件時,我收到了此類消息。
有人可以告訴我我在這里做錯什么嗎?
謝謝
我發現我做錯了。 感謝Mr.KraneBird
我從這里更改我的ajax代碼
$.ajax({
type: 'POST',
url: 'downloadfiles',
data: {value: str},
success: function(data) {
alert('ok' + data);
}
});
為此。
window.location.href = "<?php echo base_url().'downloadfiles/'?>" + str;
現在我沒有將其發布到download_controller,而是重定向到download_controller。
現在它運行良好,沒有任何錯誤。
謝謝所有浪費您寶貴時間來幫助我的人。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.