文件下载默认保存名

在前端使用a标签下载文件,浏览器会自动打开文件预览。可以使用html5的download属性来实现下载。
如:

1
<a href="xx.pdf" download>下载</a>

如果需要指定文件名,则可以写成:
1
<a href="xx.pdf" download="filename">下载</a>

如果需要修改后缀,则可以写成:
1
<a href="xx.pdf" download="filename.doc">下载</a>

问题:

如果跨域了,在chorme浏览器下,可以下载,但是下载的文件名设置无效,如:

1
<a href="xx.pdf" download="filename.doc">下载</a>

下载下来的文件名仍然为xx.pdf,解决文件名问题有2个方法:

方法一:

在服务器端下载文件,并在http请求头里设置Content-Disposition,如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php
$file = "/tmp/中文名.tar.gz";

$filename = basename($file);

header("Content-type: application/octet-stream");

//处理中文文件名
$ua = $_SERVER["HTTP_USER_AGENT"];
$encoded_filename = rawurlencode($filename);
if (preg_match("/MSIE/", $ua)) {
header('Content-Disposition: attachment; filename="' . $encoded_filename . '"');
} else if (preg_match("/Firefox/", $ua)) {
header("Content-Disposition: attachment; filename*=\"utf8''" . $filename . '"');
} else {
header('Content-Disposition: attachment; filename="' . $filename . '"');
}

//让Xsendfile发送文件
header("X-Sendfile: $file");

方法二:

可以在nginx里设置,将传入的文件名写入Content-Disposition,nginx.conf配置如下:

1
2
3
4
5
6
7
location / {
root /var/www/doc/;
if ($request_uri ~* ^.*\/(.*)\.(doc|txt|pdf)(\?n=([^&]+))$){
add_header Content-Disposition "attachment;filename=$arg_n.$2";
}
index index.html index.htm;
}

在浏览器里数据http://showmecode.cn/xx.pdf?n=myname,下载的文件名即为myname.pdf

参考
了解HTML/HTML5中的download属性