如果用户单击要下载的文件,我希望浏览器在可以的情况下显示内容(PDF、图像),否则下载。对于 PDF 和图像,如果他们选择下载文件,我希望对话框中包含正确的文件名。我的代码是:
header("Content-type: $mime");
header("Content-Disposition: attachment; filename=\"$name\"");
//send the file contents to the browser
这会导致文件一直被下载。我需要传递额外的标头参数吗?
答案 0 :(得分:1)
试试这个。这样做的作用是传入一个文件,如果文件是PDF,那么它会将文件交给浏览器,然后浏览器会读取该文件。
<?php
// Store the file name into variable
$file = 'FileName.pdf';
$filename = 'FileName.pdf';
// Header content type
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');
// Read the file
@readfile($file);
?>
参考:
答案 1 :(得分:0)
$extenionsAllowed = ['pdf','png','jpg']; // fill all here.
// converting the extension into small case
$extension = strtolower(pathinfo($file, PATHINFO_EXTENSION));
// if one of the files that are to be shown
if(in_array($extension,$extenionsAllowed)){
if($extension == 'pdf'){
// pdfs are shown differently in browsers than image files
}
// code to show file
}
else{
//code to download
}
您需要调整标题以将 pdf 显示到浏览器中,对于图像,您可以直接打开它们。在这里阅读: