I want the user to be able to download some files I have on my server, but when I try to download file shows error like below.
public function saveattachment(){
$fn=$this->input->get_post('fn');
$userid=$this->input->get_post('autherid');
$file_url = realpath("./private").$userid."/".$fn;
$file_name =basename($file_url);
$ext = explode(".", $file_name);
switch($ext[sizeof($ext)-1])
{
case 'jar': $mime = "application/java-archive"; break;
case 'zip': $mime = "application/zip"; break;
case 'jpeg': $mime = "image/jpeg"; break;
case 'jpg': $mime = "image/jpg"; break;
case 'jad': $mime = "text/vnd.sun.j2me.app-descriptor"; break;
case "gif": $mime = "image/gif"; break;
case "png": $mime = "image/png"; break;
case "pdf": $mime = "application/pdf"; break;
case "txt": $mime = "text/plain"; break;
default: $mime = "application/force-download";
}
header('Content-Description: File Transfer');
header('Content-Type: '.$mime);
header('Content-Disposition: attachment; filename='.basename($file_name));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file_url));
ob_clean();
flush();
echo $file_url;
}
The file is downloaded but its not opening.
header() must be called before any actual output is sent, Sample Code
<?php
header("Content-type:application/pdf");
// It will be called file_name_for_download.pdf
header("Content-Disposition:attachment;filename='file_name_for_download.pdf'");
// The PDF source is file_for_read.pdf
readfile("file_for_read.pdf");
?>
In your case use basic code and make sure its working fine, then add additional code as per requirements
Replace echo $file_url;
by readfile($file_url);
I got it. I had coded as header('Content-Length: ' . filesize($file_url));
and i replaced this by header('Content-Length: ' . filesize($file_name));
. Now its working. Thanks all for your time to help me.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.