How to set name of file downloaded from browser?

≯℡__Kan透↙ 提交于 2019-11-27 08:33:10
Palantir

Can't find a way in HTML. I think you'll need a server-side script which will output a content-disposition header. In php this is done like this:

header('Content-Disposition: attachment; filename="downloaded.pdf"');

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

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

In fact, it is the server that is directly serving your files, so you have no way to interact with it from HTML, as HTML is not involved at all.

Mephiztopheles

When they click a button to download the file, you can add the HTML5 attribute download where you can set the default filename.

That's what I did, when I created a xlsx file and the browser want to save it as zip file.

<a href="path/to/file" download="renamed.txt">Download</a>
<a href="downloads/export.xlsx" download="Data-Export.xlsx">Download Export</a>

it's very easy by using HTML5 download attribute!

here is my codepen demo.

https://codepen.io/xgqfrms/full/GyEGzG/

my screen shortcut.

add gif demo.

This will have to be done on the server side. You will have to have the old file name in a database somewhere, and then you could move it to a temp folder with the correct name and send that file to the user. TBQH i think you should consider avoiding name clashes with sub directories and store the path to each file in your database instead of old name / new name.

cusspvz

Well, @Palantir's answer is, for me, the most correct way!

If you plan to use that with multiple files, then i suggest you to use (or make one) PHP Download Manager.

BUT, if you want to make that to one or two files, I will suggest you the mod_rewrite option:

You have to create or edit your .htaccess file on htdocs folder and add this:

RewriteEngine  on 
RewriteRule ^abc\.txt$  xyz.txt

With this code, users will download xyz.txt data with the name abc.txt

NOTE: Verify if you have already the "RewriteEngine on " on your file, if yes, add only the second for each file you wish to redirect.

Good Luck ;) (Sorry for my english)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!