php 下载时重命名文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1801076/
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
Renaming files when downloading it
提问by Boffin
I want to rename file when user downloads it.
我想在用户下载文件时重命名文件。
Right now, I'm sending content-disposition and content-length headers and then send file to user with fpassthru PHP function.
现在,我正在发送 content-disposition 和 content-length 标头,然后使用 fpassthru PHP 函数将文件发送给用户。
But there is 3 problems with this method:
但是这种方法有 3 个问题:
- If I'm sending big (above 3-4Gb) files this way, then my PHP script runs too much time and may be killed by timeout.
- If user cancels the download, PHP script continue to read and send the file
- If user pauses the download, he cannot resume it later.
- 如果我以这种方式发送大(3-4Gb 以上)文件,那么我的 PHP 脚本运行时间过长,可能会因超时而终止。
- 如果用户取消下载,PHP 脚本会继续读取并发送文件
- 如果用户暂停下载,他将无法在以后继续下载。
Is there any nicer way to rename files on download?
有没有更好的方法来重命名下载的文件?
回答by RienNeVaPlu?s
Since the question was asked, some time has gone by and html5gave us a different approach to this:
自从提出这个问题以来,一段时间过去了,html5给了我们一种不同的方法来解决这个问题:
<a href="someWeiredFileName.rar" download="coolFilename.rar">Download</a>
The attributedownload(learn more) defines the default filenamefor storing the file on the clients computer (he'll still be able to change it!).
该attribute下载(了解更多)定义了默认filename存储在客户计算机上的文件(他仍然能够去改变它!)。
Note: this won't affect anything on your server.
注意:这不会影响您服务器上的任何内容。
回答by powtac
<?php
header('Content-type: application/pdf');
// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');
// The PDF source is in original.pdf
readfile('original.pdf');
?>
- The file will be offered for download as "downloaded.pdf" while its original name was "original.pdf".
- 该文件将作为“downloaded.pdf”提供下载,而其原始名称为“original.pdf”。
Pseudo code
伪代码
while(1) {
Echo "..."; //<-- send this to the client
if (connection_status()!=0){
die;
}
}
You can stop the PHP script if a user cancels the browser by using
connection_status()HTTP can not reconnect a closed connection. FTP can!
如果用户使用以下命令取消浏览器,您可以停止 PHP 脚本
connection_status()HTTP 无法重新连接已关闭的连接。FTP可以!
回答by Atli
For the third point, you could try using the HTTP Rangeheaders.
If the user has a resume-capable download client, it should send those headers to your script, which you could use to pinpoint exactly which parts of the file to send.
对于第三点,您可以尝试使用HTTP 范围标头。
如果用户有一个支持恢复的下载客户端,它应该将这些标头发送到您的脚本,您可以使用它来精确确定要发送的文件部分。

