php 实现图片下载,文件下载

1.控制器
public function downPic(){
$filename = input('file','','string'); //文件所在路径
// 检查文件是否存在
if (! file_exists($filename) ) {
$this->error('文件未找到');
}else{
$fileinfo = pathinfo($filename);
header('Content-type: application/x-' . $fileinfo['extension']);
header('Content-Disposition: attachment; filename=' . $fileinfo['basename']);
readfile($filename);
exit();
}
}
//下载文件  //$file需要下载的文件  $name 为下载后文件名(后缀要一致)
function commonDownFile($file,$name){
if(!file_exists($file)){
return false;
}else{
header("Content-length: ".filesize($file));
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . $name . '"');
readfile("$file");
}
}

注:thinkphp5.1中可以直接调用download
public function downPic{
return download('image.jpg','my'); //下载image.jpg图片,命名为my.jpg
}
2.html中,js直接访问,或者直接用href链接
function downPic() {
var pic = $('#show_pic').attr('src');
window.location.href = "{:url('/home/downPic')}"+'?file='+pic;
}
posted @ 2020-06-24 16:00  北往星辰  阅读(519)  评论(0编辑  收藏  举报