寫程式的人,很不喜歡遇到檔案處理,偏偏我接到幾種檔案處理的需求,一夕之間讓我變成檔案處理達人(大誤)
以下介紹蘭花寫過的四種上傳、下載的方法。程式碼僅截取與主題相關部份。
※上傳Client PC的檔案至虛擬路徑資料夾
這是最基本的功能,採用ASP .NET提供的FileUpload元件,就可以輕鬆完成。
Client Side:
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="ButtonUpload" runat="server" Text="上傳"/>
Server Side:
Imports System.IO
.
.
.
Protected Sub ButtonUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ButtonUpload.Click
Call FileUpload()
End Sub
Protected Sub FileUpload()
Dim Path As String = Server.MapPath("../Docs") ' 定義上傳後存檔路徑
Dim FileOK As Boolean = False ' 判斷是否上傳成功,預設為False
Dim FileExtension As String = "" ' 存放檔案格式(副檔名)
Dim AllowedExtensions As String() = {".jpg", ".jpeg", ".png", ".gif", ".doc", ".xls", ".txt"} ' 定義允許的檔案格式
If Me.FileUpload1.HasFile Then ' 判斷是否有檔案上傳
FileExtension = IO.Path.GetExtension(Me.FileUpload1.FileName).ToLower ' 取得檔案格式
For i As Integer = 0 To AllowedExtensions.Length - 1 ' 逐一檢查允許的格式中是否有上傳檔案的格式
If FileExtension = AllowedExtensions(i) Then
FileOK = True
Exit For
End If
Next
If FileOK Then
Try
Me.FileUpload1.PostedFile.SaveAs(Path & "/" & Me.FileUpload1.FileName) ' 儲存上傳檔案
ut.MessageBox("檔案上傳成功!", MsgBoxStyle.Information, Me.Page) ' ut是自行編寫的共用程式
Catch ex As Exception
ut.MessageBox("檔案上傳失敗!<br/>" + ex.Message, MsgBoxStyle.Information, Me.Page)
End Try
Else
ut.MessageBox("該檔案格式不允許上傳!請確認欲上傳檔案的格式是否正確!", MsgBoxStyle.Information, Me.Page)
End If
End If
End Sub
※上傳Client PC的檔案至SQL Server
利用ASP .NET提供的FileUpload元件,將使用者上傳的檔案儲存至資料庫,以便系統後續再查閱。
Client Side:
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Button ID="ButtonUpload" runat="server" Text="上傳"/>
.
.
.
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
SelectCommand="SELECT * FROM [File] ORDER BY [FileID]" DeleteCommand="DELETE FROM [File] WHERE [FileID] = @ FileID " ProviderName="<%$ ConnectionStrings:DBConnectionString.ProviderName %>">
</asp:SqlDataSource>
Server Side:
Protected Sub ButtonUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim FileName As String = "" ' 儲存至資料庫的檔名
Dim startIndex As Integer = 0 ' 截取檔名用
Dim endIndex As Integer = 0 ' 截取檔名用
Dim myFL As FileUpload
Try
myFL = CType(Me.FindControl("FileUpload1"), FileUpload)
If myFL.PostedFile.ContentLength > 0 Then ' 判斷是否有選取檔案
FileName = myFL.PostedFile.FileName
startIndex = FileName.LastIndexOf("\") + 1
endIndex = FileName.Length() - startIndex
FileName = FileName.Substring(startIndex, endIndex)
If cn.State = System.Data.ConnectionState.Closed Then
cn.ConnectionString = Me.SqlDataSource1.ConnectionString
cn.Open()
End If
' 執行檔案上傳
cmd.Connection = cn
cmd.CommandText = "INSERT INTO File (FileName, FileImage) VALUES (N'" & FileName & "', @FileImage)"
cmd.Parameters.Add(New System.Data.SqlClient.SqlParameter("@FileImage", Data.SqlDbType.Binary))
cmd.Parameters(0).Value = myFL.FileBytes
cmd.ExecuteNonQuery()
msg = "檔案上傳成功!"
cn.Close()
Else
msg = "請選取檔案!"
End If
Catch ex As Exception
msg = "檔案上傳失敗!原因:" & ex.ToString
End Try
If msg <> "" Then
ut.MessageBox(msg, MsgBoxStyle.Information, Me.Parent.Page) ' ut是自行編寫的共用程式
End If
End Sub
※下載虛擬路徑資料夾的檔案
有上傳,就要可以下載。
我的下載方式會先做個動態HyperLink清單。所謂動態就是隨著虛擬路徑資料夾、SQL Server裡存放的內容變化而變化,不是寫死的。
HyperLink的NavigateUrl再分別指定路徑,開啟專門下載檔案用的網頁。
HyperLink清單對寫程式的人而言,應該很簡單吧!就不贅述。
以下範例僅示範專門下載檔案用的網頁。
Client Side:
依需求而定。
我的範例則是空空如也。
Server Side:
Imports System.IO
.
.
.
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
' 從HyperLink的NavigateUrl指定兩個參數:FilePath(欲開啟檔案的虛擬路徑)、FileName(欲開啟檔案的檔名)
If Request.QueryString("FilePath").ToString <> "" Then
Dim FileName As String = Request.QueryString("FileName").ToString
Response.ClearHeaders()
Response.Clear()
Response.Expires = 0
Response.Buffer = True
Response.AddHeader("Accept-Language", "zh-tw")
' 檔案名稱
Response.AddHeader("Content-Disposition", "attachment; filename=" & Chr(34) & System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) & Chr(34))
Response.ContentType = "Application/octet-stream"
' 檔案內容
Response.WriteFile(Request.QueryString("FilePath").ToString)
Response.End()
End If
End If
Catch ex As Exception
End Try
End Sub
※下載SQL Server的檔案
我的下載方式會先做個動態HyperLink清單。所謂動態就是隨著虛擬路徑資料夾、SQL Server裡存放的內容變化而變化,不是寫死的。
HyperLink的NavigateUrl再分別指定路徑,開啟專門下載檔案用的網頁。
HyperLink清單對寫程式的人而言,應該很簡單吧!就不贅述。
以下範例僅示範專門下載檔案用的網頁。
Client Side:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings: DBConnectionString %>" SelectCommand="SELECT * FROM [File] ORDER BY [FileID]">
</asp:SqlDataSource>
Server Side:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
' 從HyperLink的NavigateUrl指定一個參數:FileID(欲開啟檔案的檔案編號)
If Request.QueryString("FileID").ToString <> "" Then
Me.SqlDataSource1.SelectCommand = "SELECT * FROM File WHERE FileID ='" & Request.QueryString("FileID") & "'"
End If
Dim dv As Data.DataView = Me.SqlDataSource1.Select(New DataSourceSelectArguments)
' 準備下載檔案
Response.ClearHeaders()
Response.Clear()
Response.Expires = 0
Response.Buffer = True
Dim FileName As String = dv.Item(0).Item("FileName")
' 透過 Header 設定檔名
Response.AddHeader("Content-Disposition", "attachment; filename=" & Chr(34) & System.Web.HttpUtility.UrlEncode(IO.Path.GetFileName(FileName), System.Text.Encoding.UTF8) & Chr(34))
Response.ContentType = "Application/octet-stream"
' 傳出要讓使用者下載的內容
Response.BinaryWrite(dv.Item(0).Item("FileImage"))
' 釋放資源
Response.End()
End If
Catch ex As Exception
End Try
End Sub