php 下载与存储名称不同的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1628260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 03:19:26  来源:igfitidea点击:

Downloading a file with a different name to the stored name

phpdownloadhttp-headers

提问by Utku Dalmaz

Is it possible to let your user download a file with a different name?

是否可以让您的用户下载具有不同名称的文件?

For example, there is a file called "4324ffsd34.jpg". I want people to download it via download.php, with a different name (like "filetodownload.jpg"), without renaming the original file.

例如,有一个名为“4324ffsd34.jpg”的文件。我希望人们通过 download.php 下载它,使用不同的名称(如“filetodownload.jpg”),而不重命名原始文件。

回答by David Snabel-Caunt

Sure, use a Content-disposition header

当然,使用 Content-disposition标头

header('Content-Disposition: attachment; filename="filetodownload.jpg"');

if you wish to provide a default filename, but not automatic download, this seems to work.

如果您希望提供默认文件名,而不是自动下载,这似乎可行。

header('Content-Disposition: filename="filetodownload.jpg"');

回答by Frankie

Sure you can, just try something like this:

当然可以,只需尝试以下操作:

$original_filename = '4324ffsd34.jpg';
$new_filename = 'my_new_filename_is_detailled.jpg';

// headers to send your file
header("Content-Type: application/jpeg");
header("Content-Length: " . filesize($original_filename));
header('Content-Disposition: attachment; filename="' . $new_filename . '"');

// upload the file to the user and quit
readfile($original_filename);
exit;

Hope it helps!

希望能帮助到你!

回答by The Bumpaster

There is also another way if you are using html5

如果您使用的是 html5,还有另一种方法

<a href="link/to/my/file/with/a/name/i/dont/like.jpg" download="MyFile.jpg">Download</a>

Cheers :3

干杯:3

回答by Gayan Dasanayake

<a href="4324ffsd34.jpg" download="filetodownload">Download</a>

回答by user2685840

Nothing wrong with the above but I had to add:

以上没有错,但我不得不补充:

ob_clean();
flush();

before readfile

在读取文件之前

otherwise I can not open the download jpg/png file

否则我无法打开下载的 jpg/png 文件