基於網頁的所見即所得編輯器在新聞與文章系統裡越用越廣,從別的網頁貼一段進來就能保留原樣式,連圖片都一起帶過來。問題是來源頁的圖片一旦失效,你的文章裡就留下一個大大的紅色 X。
以往只能手動把圖片存下、重新上傳、再改連結,麻煩至極。能不能讓伺服器自動抓圖存到本地並替換連結?可以,分三步走。
方法很多,字串切割也行,但實測正則表達式最省事。分析後可知圖片網址都在 <img> 標籤裡,所以採兩層匹配:先抓標籤,再抓標籤內的網址。
Set objRegExp = New Regexp ' 設定配置物件
objRegExp.IgnoreCase = True ' 忽略大小寫
objRegExp.Global = True ' 全文搜尋
objRegExp.Pattern = "<img.+?>" ' 先取出所有 img 標籤
strs = Trim(str)
Set Matches = objRegExp.Execute(strs) ' 開始執行匹配
For Each Match In Matches
RetStr = RetStr & getimgs(Match.Value) ' 第二輪匹配,取出網址
Next
第二輪的 getimgs 函數:
Function getimgs(str)
getimgs = ""
Set objRegExp1 = New Regexp
objRegExp1.IgnoreCase = True
objRegExp1.Global = True
objRegExp1.Pattern = "https://.+?""" ' 取出裡面的網址
Set mm = objRegExp1.Execute(str)
For Each Match1 In mm
getimgs = getimgs & "" & Left(Match1.Value, Len(Match1.Value) - 1)
Next
End Function
這裡用非貪婪的 .+? 配合結尾的引號,只取到 src 屬性的值為止,不會一路吃到標籤結尾。
抓取內容用 XMLHTTP:
Function getHTTPPage(url)
On Error Resume Next
Dim http
Set http = Server.CreateObject("MSXML2.XMLHTTP") ' 用 XMLHTTP 取得圖片內容
http.Open "GET", url, False
http.Send()
If http.readyState <> 4 Then Exit Function
getHTTPPage = http.responseBody ' 必須用 responseBody,responseText 會破壞二進位
Set http = Nothing
If Err.Number <> 0 Then Err.Clear
End Function
存檔這步直覺上會想用 FSO,但實際上行不通——FSO 不支援流式寫入。要改用 ADODB.Stream:
Function saveimage(from, tofile)
Dim geturl, objStream, imgs
geturl = Trim(from)
imgs = gethttppage(geturl) ' 取得圖片的具體內容
Set objStream = Server.CreateObject("ADODB.Stream") ' 需 ADO 2.5 以上
objStream.Type = 1 ' 以二進位模式開啟
objStream.Open
objStream.Write imgs ' 寫入緩衝
objStream.SaveToFile Server.MapPath(tofile), 2 ' 2 = 覆寫
objStream.Close()
Set objStream = Nothing
End Function
接著用迴圈把取到的網址逐一存下:
arrimg = Split(retstr, "") ' 切出網址清單
allimg = ""
newimg = ""
For i = 1 To UBound(arrimg)
If arrimg(i) <> "" And InStr(allimg, arrimg(i)) < 1 Then ' 檢查是否已下載過
fname = baseurl & CStr(i & Mid(arrimg(i), InStrRev(arrimg(i), ".")))
saveimage arrimg(i), fname ' 存檔
allimg = allimg & "" & arrimg(i) ' 記錄已處理的來源網址
newimg = newimg & "" & fname ' 記錄本地新網址
End If
Next
arrnew = Split(newimg, "") ' 本地圖片清單
arrall = Split(allimg, "") ' 原圖片清單
For i = 1 To UBound(arrnew)
strs = Replace(strs, arrall(i), arrnew(i))
Next
cctv = strs
這個函數還能再加料:限制圖片大小上限、排除本站圖片避免重複下載、比對副檔名白名單等。
但有三個限制要清楚:一是只能處理靜態圖片檔,程式動態產生的圖形無效;二是抓來源檔名時若未做檢核,惡意網址可能造成寫檔位置不預期,實務上應自行產生檔名而非沿用來源檔名;三是迴圈同步抓取多張圖會讓請求逾時,圖片多時應改為背景批次處理。