我想制作一个网站,可以下载jpg,png,pdf,docx文件,这些文件由管理员上传。使用codeigniter下载现有的文件
上传这些内容工作没有问题。上传时,我也将该文件名插入到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文件时,我收到了这样的消息。
可以有一个人告诉我什么是错误的事情我'在这里做什么?
谢谢你
您是否需要通过Ajax下载文件?如果您将链接设置为'downloadfiles' url,它将下载该文件并保持在同一页面上。 –
你尝试过force_download吗? –
@KraneBird - 你能否给我正确的方法来做到这一点?仍然我无法正确 谢谢你 – Yasitha