需從遠程 URL 下載圖片、文檔、視頻並保存至伺服器?Microsoft.XMLHTTP 獲取二進制數據流,ADODB.Stream 寫入本地檔案,純 ASP 實現無組件下載。
<%
Function SaveRemoteFile(localFileName, remoteFileUrl)
On Error Resume Next
SaveRemoteFile = True
Dim xmlhttp, binData, stream
' 1. 獲取遠程二進制數據
Set xmlhttp = Server.CreateObject("Microsoft.XMLHTTP")
With xmlhttp
.Open "GET", remoteFileUrl, False ' 同步模式
.Send
If .ReadyState <> 4 Or .Status <> 200 Then
SaveRemoteFile = False
Set xmlhttp = Nothing
Exit Function
End If
binData = .ResponseBody ' 關鍵:ResponseBody 返回二進制字節數組
End With
Set xmlhttp = Nothing
' 2. 寫入本地檔案
Set stream = Server.CreateObject("ADODB.Stream")
With stream
.Type = 1 ' adTypeBinary
.Open
.Write binData
.SaveToFile Server.MapPath(localFileName), 2 ' 2 = adSaveCreateOverWrite
.Close
End With
Set stream = Nothing
If Err.Number <> 0 Then SaveRemoteFile = False
End Function
%>
<%
Dim remoteUrl, localFile, ext
remoteUrl = "https://www.example.com/logo.gif"
' 生成唯一檔名:時間戳 + 原副檔名
ext = Right(remoteUrl, 4) ' 簡易取 .gif/.jpg/.png
If InStr(ext, ".") = 0 Then ext = ".bin"
localFile = Replace(Replace(Replace(Now(), "-", ""), ":", ""), " ", "") & ext
If SaveRemoteFile(localFile, remoteUrl) Then
Response.Write "成功保存:" & localFile & " (" & Round(FileLen(Server.MapPath(localFile))/1024, 1) & " KB)"
Else
Response.Write "下載失敗,請檢查遠程 URL 或權限"
End If
%>
Microsoft.XMLHTTP | .ResponseBody | 獲取原始二進制數據 (避免字符編碼損壞) |
| ADODB.Stream | .Type = 1 | 二進制模式 |
| | .SaveToFile path, 2 | 2 = adSaveCreateOverWrite 覆蓋寫入 |
| | .Cancel / .Close | 釋放鎖定 |
Function SaveRemoteFileEx(remoteUrl, localPath, Optional timeoutSec = 30)
Dim xmlhttp, stream, startTime
Set xmlhttp = Server.CreateObject("MSXML2.ServerXMLHTTP.6.0") ' 更穩健
xmlhttp.SetTimeouts timeoutSec*1000, timeoutSec*1000, timeoutSec*1000, timeoutSec*1000
xmlhttp.Open "GET", remoteUrl, False
xmlhttp.Send
If xmlhttp.Status <> 200 Then
SaveRemoteFileEx = "HTTP " & xmlhttp.Status
Exit Function
End If
' 大文件分塊寫入 (模擬流式,實際 XMLHTTP 會全量緩存)
Set stream = Server.CreateObject("ADODB.Stream")
stream.Type = 1
stream.Open
stream.Write xmlhttp.ResponseBody
stream.SaveToFile localPath, 2
stream.Close
SaveRemoteFileEx = "OK"
End Function
Content-Length Header)幾十行代碼實現生產級遠程文件下載,是 ASP 時代「雲同步」的基石技能。