瀏覽器直接存取 .doc、.xls、.jpg 等檔案時,預設會嘗試內嵌開啟。若需強制彈出「另存新檔」對話框,需透過 HTTP 標頭控制。
application/octet-stream,但會影響全站同類檔案。<%
Response.Buffer = True
Response.Clear
Dim url, fso, fl, flsize, flName
Dim objStream, ContentType, Dname
' 取得下載檔名參數
Dname = Trim(Request("n"))
If Dname <> "" Then
url = Server.MapPath("/") & Dname
End If
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Set fl = fso.GetFile(url)
flsize = fl.Size
flName = fl.Name
Set fl = Nothing
Set fso = Nothing
%>
<%
Set objStream = Server.CreateObject("ADODB.Stream")
objStream.Open
objStream.Type = 1 ' 二進位
objStream.LoadFromFile url
' 依副檔名決定 Content-Type
Select Case LCase(Right(flName, 4))
Case ".asf" : ContentType = "video/x-ms-asf"
Case ".avi" : ContentType = "video/avi"
Case ".doc" : ContentType = "application/msword"
Case ".zip" : ContentType = "application/zip"
Case ".xls" : ContentType = "application/vnd.ms-excel"
Case ".gif" : ContentType = "image/gif"
Case ".jpg", "jpeg" : ContentType = "image/jpeg"
Case ".wav" : ContentType = "audio/wav"
Case ".mp3" : ContentType = "audio/mpeg3"
Case ".mpg", "mpeg" : ContentType = "video/mpeg"
Case ".rtf" : ContentType = "application/rtf"
Case ".htm", "html" : ContentType = "text/html"
Case ".txt" : ContentType = "text/plain"
Case Else : ContentType = "application/octet-stream"
End Select
Response.AddHeader "Content-Disposition", "attachment; filename=" & flName
Response.AddHeader "Content-Length", flsize
Response.Charset = "UTF-8"
Response.ContentType = ContentType
Response.BinaryWrite objStream.Read
Response.Flush
objStream.Close
Set objStream = Nothing
%>
Content-Disposition: attachment; filename=... → 強制下載並指定預設檔名Content-Length → 讓瀏覽器顯示下載進度條Content-Type → 告知瀏覽器檔案類型,搭配 attachment 可避免內嵌開啟ADODB.Stream Type=1 → 二進位讀取,支援任意檔案格式Request("n"),防止目錄遍歷攻擊(如 ../../web.config)。