此檔案會從被呼叫的網址收集scid參數,當成資料庫下載的主要鍵
<%@ WebHandler Language="VB" Class="download" %>
'----------------------------------------------------------------------------
'程式功能 檔案上傳下載 (以資料庫存放檔案) > 檔案下載
'----------------------------------------------------------------------------
Imports System
Imports System.Data.SqlClient
Imports System.Web
Imports System.Web.Configuration
Imports System.Web.SessionState ' 要使用 Session 必需加入此命名空間
Public Class download : Implements IHttpHandler, IRequiresSessionState
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'context.Response.ContentType = "text/plain"
'context.Response.Write("Hello World")
Dim mErr As String = ""
Dim scid2 As Integer = -1
' 檢查使用者權限,但不存入登入紀錄
'Check_Power("2002", False, context)
If context.Request("scid") IsNot Nothing Then
If Integer.TryParse(context.Request("scid").Trim(), scid2) Then
' 處理下載檔案
Using Sql_conn As New SqlConnection(WebConfigurationManager.ConnectionStrings("AppSysConnectionString").ConnectionString)
Sql_conn.Open()
Using Sql_Command As New SqlCommand()
Dim SqlString As String = ""
SqlString = "Select Top 1 fname, ftype, fcontent From 學生證照2 Where scid2 = @scid2"
Sql_Command.Connection = Sql_conn
Sql_Command.CommandText = SqlString
Sql_Command.Parameters.AddWithValue("scid2", scid2)
Dim Sql_Reader As SqlDataReader = Sql_Command.ExecuteReader()
If Sql_Reader.Read() Then
Dim fcontent As Byte() = DirectCast(Sql_Reader("fcontent"), Byte())
context.Response.Clear()
context.Response.Charset = "utf-8"
' 檔名要先編碼,中文檔名才不會有問題
context.Response.AddHeader("Content-Disposition", "inline;filename=" & context.Server.UrlEncode(Sql_Reader("fname").ToString().Trim()))
context.Response.ContentType = Sql_Reader("ftype").ToString()
context.Response.BinaryWrite(fcontent)
context.Response.End()
Else
mErr = "找不到這個檔案的資料!\n"
End If
End Using
End Using
Else
mErr = "參數傳送有問題!\n"
End If
Else
mErr = "參數傳送有問題!\n"
End If
If mErr <> "" Then
context.Response.ContentType = "text/html"
context.Response.Write(mErr)
context.Response.End()
End If
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
而另外有一個 filedelete_download.aspx 來呼叫剛剛撰寫的 download.ashx 。
傳遞網址 download.ashx?scid={0} {0}代表的是DataNavigateUrlField的資料,也就是資料表中的主要鍵欄位。
點選下載後,如果是圖形會直接開新視窗顯示圖片,如果是其他檔案會詢問開啟, 儲存 或 取消
當我們要實作刪除功能時,首先必須修改 sqldatasource ,設定sqldatasource資料來源時,刪除delete指令需要修改,改成
DELETE FROM [學生證照2] WHERE [scid2] = @original_scid2
接著從 gridview 啟用刪除即可,必要時可用編輯資料行調整左右位置
沒有留言:
張貼留言