接着您可以通过下面的代码进行文件的上传:
If Me.FileUpload1.PostedFile.ContentLength > 0 Then
Dim cn As New Data.OleDb.OleDbConnection
Dim dc As Data.OleDb.OleDbCommand
Dim para As Data.OleDb.OleDbParameter
Dim SQL, FileName As String
'连线字符串
cn.ConnectionString = Me.AccessDataSource1.ConnectionString
cn.Open()
'运行 TextBox 中的 SQL 指令
FileName = Me.FileUpload1.PostedFile.FileName
SQL = "insert into FileStorage (FileName,FileBody) values ('" & FileName & "',?)"
'建立 SqlCommand 对象
dc = New Data.OleDb.OleDbCommand(sql, cn)
para = New Data.OleDb.OleDbParameter("file", Data.OleDb.OleDbType.Binary)
para.Value = Me.FileUpload1.FileBytes
dc.Parameters.Add(para)
'运行(通过 Parameters 将文件存储到数据库)
dc.ExecuteNonQuery()
ShowAlertMsg("上传文件存储完毕!")
Else
ShowAlertMsg("上传文件不存在!")
End If
上传至数据库中的文件,可以通过下面的方式重新下载回来,请特别这注意这张网页在调用的时候必须提供文件编号做为URL中的命令行参数:
Me.AccessDataSource1.SelectCommand = "select * from FileStorage where uid=" & Request.QueryString("FileID")
Dim dv As Data.DataView = Me.AccessDataSource1.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("FileBody"))
'释放资源
Response.End()