現(xiàn)在的瀏覽器能夠識別很多文件類型(txt,pdf,jpg...),并在瀏覽器中自動打開
情況一:
添加頭信息Content-Disposition "attachment;"會使瀏覽器強(qiáng)制下載:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
代碼如下:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
#表示瀏覽器內(nèi)嵌顯示一個(gè)文件 Content-disposition: inline; filename=foobar.pdf #表示會下載文件,如火狐瀏覽器中 Content-disposition: attachment; filename=foobar.pdf
nginx配置如下,在相應(yīng)的server中添加如下location:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
代碼如下:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
location /download { add_header Content-Disposition "attachment;"; }
情況二:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
有這么一個(gè)需求,對于圖片文件和pdf等文件鏈接,只要訪問實(shí)在某個(gè)路徑下,不能在瀏覽器中打開圖片,而是提示用戶保存到本地,文件名使用訪問的文件名。
這個(gè)問題主要是IE造成的,不管mime類型是什么,比如人工把圖片的mime類型設(shè)置為octet-stream,如果瀏覽器認(rèn)識文件后綴的話,仍然會在瀏覽器中打開圖片。文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
解決方案:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
在響應(yīng)的http頭添加:Content-Disposition: attachment; filename=文件名
nginx配置如下:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
代碼如下:文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
location ~ ^/somepath/(.*)$ { add_header Content-Disposition "attachment; filename=$1"; alias "E:/apache-tomcat-7.0.32/webapps/upload/$1"; }
這里使用到了正則表達(dá)式,捕獲請求的文件名。
另外,需要注意nginx的location優(yōu)先級,首先是=,然后是^~,最后才是~。文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
基本上,您需要在要強(qiáng)制下載的 URL 的位置塊中添加以下行。文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
add_header Content-disposition "attachment; filename=$1"; default_type application/octet-stream;
上面兩行將內(nèi)容處置標(biāo)頭設(shè)置為“附件”,將內(nèi)容類型設(shè)置為“應(yīng)用程序/八位字節(jié)流”以啟用下載。文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
例如,如果您想對以 /downloads 開頭的所有 URL 強(qiáng)制下載,則在該文件夾的位置塊中添加上述行,如下所示。文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
location /downloads { ... add_header Content-disposition "attachment; filename=$1"; default_type application/octet-stream; ... }
如果您想強(qiáng)制下載以某些文件類型和擴(kuò)展名(例如 .jpg、.png、.mp3 等)結(jié)尾的所有文件,請?jiān)谟糜谶@些文件類型的位置塊中添加上述 2 行。文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
location ~* ^/.+\.(?:gif|jpe?g|png|mp4|mp3)$ { ... add_header Content-disposition "attachment; filename=$1"; default_type application/octet-stream; ... }
以上修改完成后需要重啟Nginx,或重新加載文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
nginx -s reload文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html文章源自網(wǎng)吧系統(tǒng)維護(hù)-http://www.strong-digital.cn/10565.html
評論