HTTP下载文件名称编码说明

时间:2021-12-31 17:48:16

HTTP下载保存文件名

下载文件需要保存的名称 在响应报文头中 Content-Disposition 响应报文头域中指定, 例如
Content-Disposition: attachment; filename*="utf8''%E4%B8%AD%E6%96%87%20%E6%96%87%E4%BB%B6%E5%90%8D.txt"

其中filename后指定文件名称。

HTTP规范要求

  http://www.w3.org/Protocols/rfc2616/rfc2616-sec19.html

        content-disposition = "Content-Disposition" ":"
disposition-type *( ";" disposition-parm )
disposition-type = "attachment" | disp-extension-token
disposition-parm = filename-parm | disp-extension-parm
filename-parm = "filename" "=" quoted-string
disp-extension-token = token
disp-extension-parm = token "=" ( token | quoted-string )

An example is

        Content-Disposition: attachment; filename="fname.ext"
参考 http://haoyu.farbox.com/post/download-header
http://www.phpv.net/html/1675.html
http://blog.angryfox.com/?tag=%E4%B8%8B%E8%BD%BD
 

兼容性规则

各个浏览器实现的规则又和HTTP规范有些小差异。

给出转码规则代码:

-- 获取文件名
local filename = cgilua.QUERY.IF_FILENAMEUTF8
local encfilename = cgilua.urlcode.escape(filename)
encfilename = string.gsub (encfilename, "+", "%%20") -- tested '中文文 件名.txt' local useragent = sapi.Request.servervariable"HTTP_USER_AGENT"
local contentdisposition
if useragent then
if string.match( useragent, "MSIE" )
-- IE11 伪装成 mozilla, 需要借助Trident关键字区分
or string.match( useragent, "Trident" ) then
contentdisposition = 'attachment; filename="' .. encfilename .. '"'
elseif string.match( useragent, "/Firefox/" ) then
contentdisposition = "attachment; filename*=\"UTF-''"..encfilename.."\""
else
contentdisposition = 'attachment; filename="' .. filename .. '"'
end
else
contentdisposition = 'attachment; filename="' .. filename .. '"'
end