首页 > 解决方案 > 当我在 php 中单击图像名或文件名时,我想下载文件

问题描述

$path = "https://surv-translation.com/assets/uploads/files/";
$filename = "1544615073screenshot-trustwortha.com-2018.11.29-16-37-46.png";
header('Content-Transfer-Encoding: binary');  // For Gecko browsers mainly
header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($path)) . ' GMT');
header('Accept-Ranges: bytes');  // For download resume
header('Content-Length: ' . filesize($path));  // File size
header('Content-Encoding: none');
header('Content-Type: application/pdf');  // Change this mime type if the file is not PDF
header('Content-Disposition: attachment; filename=' . $filename);  // Make the browser display the Save As dialog
readfile($path);
exit;

我尝试使用此代码,但没有成功,我想下载任何文件,如 docx、pdf、ppt 或图像等。请问您能帮帮我吗?

标签: javascriptphpdownload

解决方案


您可以尝试使用此代码下载任何文件,如docpdfppt图像

if (file_exists($filepath)) {
 header('Content-Description: File Transfer');
 header('Content-Type: application/octet-stream');
 header('Content-Disposition: attachment; filename="' . basename($filepath) . '"');
 header('Expires: 0');
 header('Cache-Control: must-revalidate');
 header('Pragma: public');
 header('Content-Length: ' . filesize($filepath));
 flush(); // Flush system output buffer
 readfile($filepath);
 exit;
 }

推荐阅读