php - 如何在php中下载文件
问题描述
我想在 php 中下载图像文件。
<?php
if(isset($_REQUEST["file"])){
$filepath = BASE_URL.'assets/uploads/save_template_images/template1_221594899972.png';
// Process download
if(file_exists($filepath)) {
echo $filepath;
exit;
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);
die();
} else {
echo $filepath;
exit;
http_response_code(404);
die();
}
}
?>
在我的索引页面中,我有一个锚标记,如果单击锚标记,则运行上面的代码。我没有显示锚标记,因为我将$filepath静态值放在上面的代码中。当我运行上面的代码时,它会进入其他条件。我认为,项目的完整路径并没有被上面的代码所采用。如果我将图像放在同一个文件夹中,那么它会下载。
解决方案
首先确保打开文件中的allow_url_fopen
设置。php.ini
之后使用此代码下载您的文件:
<?php
$url = 'https://lokeshdhakar.com/projects/lightbox2/images/image-5.jpg';
$file = './files/'.basename($url);
file_put_contents($file, file_get_contents($url));
?>
要成功下载,文件目录必须存在。但我认为添加目录存在检查效率低下,因为我认为您已经知道在哪里保存正在下载的文件。
推荐阅读
- windows - 通过 ftp 脚本将文件从本地桌面文件夹批量复制到服务器上的文件夹
- c# - 安装包后找不到类型
- arrays - Angular 从 API 获取数据,只想影响数组
- windows - 使用 WSL2 后端运行时,如何在 Docker 中创建绑定挂载?
- c# - 你可以使用 microsoft bot framework 4.9 来构建一个带有 core 3.1 的 bot 吗?
- python - Python / Selenium / BeautifulSoup:如何获取需要登录的页面的html
- java - 如何使 java.util.ArrayList 线程安全
- java - 如何在 Java 中接受任何超过两位数的数字?
- firebase - 无法从 Firebase 返回查询的数据(Flutter/Dart)
- python-3.x - 尝试使用 PILLOW 和 EOG 图像查看器显示图像时出错