2008年7月7日 星期一

檔案下載solution

關於使用browser下載檔案,針對http header的設定方式,因為client端的異質性,著實讓我們吃了不少苦。以下是我認為最佳的header設定方式,同時在IE6,IE7,Firefox中work又符合user期望,雖然是用VB,但http header的部份其它language並無不同,其中有幾個地方特別值得我們注意:
1. 使用IE下載檔案,預設是用inline方式,直接開啟在browser中,此點是為了避免IE在下載檔案時的cache defect,至於其它browser,因為可用browser自身的選項決定是否直接開啟,並無設定inline需要。
2. 使用IE下載檔案,若user不想inline開啟,可教導user於下載連結處按右鍵,另存目標即可。
3. 雖然我們設定了response header是用utf-8編碼,但IE仍無法辨識特殊字元的檔名,因此檔名的部份用了url encode,但其它browser並無此問題。
4. 對firefox來說,既然已指定了response header為utf-8,此時若在對檔名進行url encode,反而會得到不符合user期望的檔名。
5. 檔名的部份,最好一定要用引號括起來,以免檔名在包含空白字完時被截斷; IE下載時,因用了url encode,故無此問題,但其它browser因未用url encode故未加引號會導致截斷。

Response.ContentType = dt.Rows(0)("file_type")

Response.AppendHeader("Content-Length", dt.Rows(0)("file_size").ToString())

If IsIe = True Then

Response.AppendHeader("Content-Disposition", "inline; filename=""" & Server.UrlEncode(dt.Rows(0)("file_name")) & """")

Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0")

Response.AddHeader("Pragma", "public")

Else

'檔名加入引號, 可避免檔名有空白時,被截斷的問題

'上方的IE,因用UrlEncode雖無此問題,但還是加

Response.AppendHeader("Content-Disposition", "attachment; filename=""" & dt.Rows(0)("file_name") & """")

Response.AddHeader("Pragma", "no-cache")

End If

Response.BinaryWrite(dt.Rows(0)("file_content"))

沒有留言: