一、需求
页面中点击下载图片
二、实现
protected function pageLoad()
{
$filePath = $_GET['file'];
$host = $_SERVER['HTTP_HOST'];
$file = 'http://'.$host.$filePath;
$fileName = basename($filePath);
$content = file_get_contents($file);
ob_clean();
$suffixArr = explode('.', $fileName);
$suffix = strtolower($suffixArr[count($suffixArr)-1]);
$suffixArr[count($suffixArr)-2] .= time();
$fileName = implode('.', $suffixArr);
$this->download($suffix, $content, $fileName);
}
private function download($extension,$content,$fileName='')
{
ob_clean();
if($content)
{
switch ($extension)
{
case 'jpg':
case 'jpeg':
case 'jpe':
case 'jfif':
header('Content-Type: image/jpeg');
if ($fileName)
{
header('Content-Disposition: attachment; filename='.$fileName);
}
break;
case 'png':
header('Content-Type: image/png');
if ($fileName)
{
header('Content-Disposition: attachment; filename='.$fileName);
}
break;
case 'bmp':
header('Content-Type: image/bmp');
if ($fileName)
{
header('Content-Disposition: attachment; filename='.$fileName);
}
break;
case 'gif':
header('Content-Type: image/gif');
if ($fileName)
{
header('Content-Disposition: attachment; filename='.$fileName);
}
break;
case 'tif':
case 'tiff':
header('Content-Type: image/tiff');
if ($fileName)
{
header('Content-Disposition: attachment; filename='.$fileName);
}
break;
case 'swf':
header("Content-type: application/x-shockwave-flash");
if ($fileName)
{
header('Content-Disposition: attachment; filename='.$fileName);
}
break;
case 'doc':
case 'docx':
case 'ppt':
case 'pptx':
$fileName = !empty($fileName)? $fileName:'';
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header('Content-Disposition: attachment; filename='.$fileName);
header("Pragma:no-cache");
header("Expires:0");
break;
case 'pdf':
$fileName = !empty($fileName)? $fileName:'';
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header('Content-Disposition: attachment; filename='.$fileName);
header("Pragma:no-cache");
header("Expires:0");
break;
case 'txt':
if ($fileName)
{
header("Content-type: application/octet-stream");
header("Accept-Ranges: bytes");
header('Content-Disposition: attachment; filename='.$fileName);
header("Pragma:no-cache");
header("Expires:0");
}
break;
case 'html':
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-Type: application/force-download");
header("Content-type: text/html");
header("Content-Disposition: attachment; filename=".$fileName);
header("Content-Description: PHP5 Generated Data");
break;
case 'xls':
case 'xlsx':
$fileName = !empty($fileName)? $fileName:'';
header("Content-type:application/octet-stream");
header("Accept-Ranges:bytes");
header("Content-type:application/vnd.ms-excel");
header('Content-Disposition: attachment;filename='.$fileName);
header("Pragma: no-cache");
header("Expires: 0");
break;
}
}
echo $content;
exit;
}