Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/231.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 我想在php中单击图像名或文件名时下载文件_Javascript_Php_Download - Fatal编程技术网

Javascript 我想在php中单击图像名或文件名时下载文件

Javascript 我想在php中单击图像名或文件名时下载文件,javascript,php,download,Javascript,Php,Download,我尝试使用这段代码,但没有成功,我想下载任何文件,如docx、pdf、ppt或image等。。那么,您能帮我吗?您可以尝试使用此代码下载任何文件,如doc、pdf、ppt或image等 $path = "https://surv-translation.com/assets/uploads/files/"; $filename = "1544615073screenshot-trustwortha.com-2018.11.29-16-37-46.png"; header('Content-Tra

我尝试使用这段代码,但没有成功,我想下载任何文件,如docx、pdf、ppt或image等。。那么,您能帮我吗?

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

$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;

“但我没有取得任何成功”——那么会发生什么呢?您可能还希望使用
Content-Type:application/octet-stream
而不是硬编码
pdf
(特别是因为代码试图下载png,而不是pdf)。您可以从这里开始
标题('Content-Type:application/pdf')但看起来您正在尝试使用png
readfile($path)
filemtime($path)
filesize($path)
也不正确
$path
只包含路径,不包含文件名。一个好的答案是解释OP为什么应该尝试此操作。它解决了什么,又是如何解决的?听着,伙计,我尽了最大努力,给他举个例子如果你有更好的答案请分享或编辑我的代码我只是想帮你写一个更好的答案。答案应该总是包含一个关于它解决了什么以及如何解决的解释。这样,OP(和未来的访问者)将学会如何在未来解决类似问题亲爱的@MagnusEriksson问题不需要任何解释,他只是想要一个例子,我试着这么做。那么为什么要编写PHP呢?你真的需要更新你的问题,你真正需要的
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;
 }