HTTP Header Content Disposition

2022-12-30

使用 HTTP Header Content-Dispoition 設定附件預設的開啟或下載行為。

logo

說明

public ActionResult PDF()
{
    var cd = new System.Net.Mime.ContentDisposition
    {
        FileName = "PDF_Sample.pdf",
        Inline = false,
    };
    Response.AppendHeader("Content-Disposition", cd.ToString());
    return File("~/Files/PDF_Sample.pdf", "Application/pdf");
}

預設上不加入 ContentDisposition 會預設使用 Inline 的方式提供 (在新頁籤開啟檔案),但如果加入 ContentDisposition 而為提供是否 Inline,則預設會使用 Attachment 的方式開啟 (逕執行檔案下載),而如果使用 Inline = True 則又會恢復為 Inline 的方式 😊

此外 ContentDisposition 的 FileName 不直接影響瀏覽器的呈現方式,但 ContentyType (MIME) 必須正確,

Common ContentType

Extension Description MIME Type
.avi AVI: Audio Video Interleave video/ x-msvideo
.bmp Windows OS/2 Bitmap Graphics image/bmp
.css Cascading Style Sheets (CSS) text/css
.csv Comma-separated values (CSV) text/csv
.doc Microsoft Word application/msword
.docx Microsoft Word (OpenXML) application/vnd.openxmlformats-officedocument.wordprocessingml.document
.gif Graphics Interchange Format (GIF) image/gif
.htm, .html HyperText Markup Language (HTML) text/html
.ico Icon format image/vnd. microsoft.icon
.jpeg, .jpg JPEG images image/jpeg
.js JavaScript text/javascript (Specifications: HTML and RFC 9239)
.json JSON format application/json
.mjs JavaScript module text/javascript
.mp3 MP3 audio audio/mpeg
.mp4 MP4 video video/mp4
.mpeg MPEG Video video/mpeg
.odp OpenDocument presentation document application/vnd.oasis.opendocument.presentation
.ods OpenDocument spreadsheet document application/vnd.oasis.opendocument.spreadsheet
.odt OpenDocument text document application/vnd.oasis.opendocument.text
.png Portable Network Graphics image/png
.pdf Adobe Portable Document Format (PDF) application/pdf
.ppt Microsoft PowerPoint application/vnd.ms-powerpoint
.pptx Microsoft PowerPoint (OpenXML) application/vnd.openxmlformats-officedocument.presentationml.presentation
.rar RAR archive application/ vnd.rar
.svg Scalable Vector Graphics (SVG) image/ svg+xml
.txt Text, (generally ASCII or ISO 8859-n) text/plain
.wav Waveform Audio Format audio/wav
.webp WEBP image image/webp
.woff Web Open Font Format (WOFF) font/woff
.woff2 Web Open Font Format (WOFF) font/woff2
.xls Microsoft Excel application/vnd.ms-excel
.xlsx Microsoft Excel (OpenXML) application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.zip ZIP archive application/zip
.7z 7-zip archive application/x- 7z-compressed

參考資料

Day20-內容要如何處置-Content-Disposition

Common MIME types