2010年12月30日 星期四

網頁用 enctype="multipart/form-data" 傳送(POST)時,用Request.Form("FieldName")讀值

當 Action的網頁採
<form method="POST" action="upload_ok.asp" name="frmUpload" enctype="multipart/form-data">
在 submit後,接受頁的Script無法直接用 Request.Form("fieldName")取得傳送頁上的值,因為傳送時已表明「表單」為multipart,即同一份內包含多重欄位,因此必須使用 Request.BinaryRead()。
Request.BinaryRead()是從Stream讀取指定長度的資料到Safe array,傳送的總長度可由 Request.TotalBytes 取得,利用Request.BinaryRead(Request.TotalBytes)即可讀取完整的資料。
可是這些資料是以Binary編碼,無法直接處理,必須經由轉碼方式才能得到文字串:

Function BinaryToString(Data,Length)
Const adLongVarChar = 201 '定義資料型別,利用ADO進行轉碼
Set RS = CreateObject("ADODB.Recordset")
RS.Fields.Append "FieldName", adLongVarChar, Length
RS.Open
RS.AddNew
RS("FieldName").AppendChunk(Data) '將binary或字元資料新增到欄位中
RS.Update
BinaryToString = RS("FieldName").Value '重新讀出欄位資料
RS.Close
End Function

當然轉碼後的只是單一字串,必須自行拆解才能得到指定欄位的值:
(1)欄位分隔碼可由字串的前 42bytes 取得 [Left(strData,42)],再利用此分隔字串拆解各欄位。
(2)字串的最後面是 chr(13)chr(10)+43byte結束字串+ chr(13)chr(10)
(2)每個欄位的各個屬性之間用「;」分隔,各組資料的第一個屬性皆為"Content-Disposition: form-data;"起頭。
(3)可從各組資料中找到「 name="欄名"[這裡有兩組chr(13)chr(10)分隔]」的屬性字串,其中「欄名」是傳送頁的欄位名稱是傳送頁上的值,兩者之間有兩組chr(13)chr(10)[即chr(13)chr(10)chr(13)chr(10)四組字元]分隔

所以由上面的規則即可自行處理欄位值了!

PostData = BinaryToString(biData,Size) '先將binary轉成字串
splitStr=left(PostData,42) '由字串前頭42byte取得分隔字串
arrPostData=Split(PostData,splitStr)
'利用分隔字串拆解各欄位

for i=0 to UBound(arrPostData) '逐一檢查欄位
If i=UBound(arrPostData) Then '最後一欄要刪除 結束字串
arrPostData=left(arrPostData,len(arrPostData)-47)
fieldData=split(arrPostData(i),";")
fieldValue=filter(fieldData,"name=")
if ubound(fieldValue)>-1 then
kk=instr(fieldValue(0),chr(13) & chr(10) & chr(13) & chr(10))
if kk >0 then
response.write mid(fieldValue(0),1,kk) & "
"
if kk <>"
end if
end if
response.write "
" 'mid(PostData,i,1)
next

沒有留言:

張貼留言