萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP 程式設計

ASP 使用 ADODB.Stream 強制下載檔案:不在瀏覽器直接開啟

問題背景

瀏覽器直接存取 .doc、.xls、.jpg 等檔案時,預設會嘗試內嵌開啟。若需強制彈出「另存新檔」對話框,需透過 HTTP 標頭控制。

兩種解決方案

  1. IIS MIME 對應:在 IIS 中將特定副檔名對應至 application/octet-stream,但會影響全站同類檔案。
  2. ASP 動態輸出(推薦):單一程式控制個別下載請求,彈性最高。

核心程式碼(含檔案類型自動判斷)

<%
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)。
  • 建議建立白名單機制,僅允許特定資料夾下的檔案下載。
  • 大檔案建議分塊輸出,避免佔用過多記憶體。
copyright © 萬盛學電腦網 all rights reserved