2012-04-13 106 views
3

我想上傳使用通用處理程序的圖像,如下所示,我有一個正常的aspx頁面,我上傳後顯示所有上傳的圖像。一切工作正常。在asp.net處理程序訪問會話

<%@ WebHandler Language="VB" Class="Upload"%> 

Imports System 
Imports System.Web 
Imports System.Threading 
Imports System.Web.Script.Serialization 
Imports System.IO 

Public Class Upload : Implements IHttpHandler, System.Web.SessionState.IRequiresSessionState 
    Public Class FilesStatus 
     Public Property thumbnail_url() As String 
     Public Property name() As String 
     Public Property url() As String 
     Public Property size() As Integer 
     Public Property type() As String 
     Public Property delete_url() As String 
     Public Property delete_type() As String 
     Public Property [error]() As String 
     Public Property progress() As String 
    End Class 
    Private ReadOnly js As New JavaScriptSerializer() 
    Private ingestPath As String 

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest 


      Dim r = context.Response 
      ingestPath = context.Server.MapPath("~/UploadedImages/") 

      r.AddHeader("Pragma", "no-cache") 
      r.AddHeader("Cache-Control", "private, no-cache") 

      HandleMethod(context) 
    End Sub 
    Private Sub HandleMethod(ByVal context As HttpContext) 
     Select Case context.Request.HttpMethod 
      Case "HEAD", "GET" 
       ServeFile(context) 

      Case "POST" 
       UploadFile(context) 

      Case "DELETE" 
       DeleteFile(context) 

      Case Else 
       context.Response.ClearHeaders() 
       context.Response.StatusCode = 405 
     End Select 
    End Sub 
    Private Sub DeleteFile(ByVal context As HttpContext) 
     Dim filePath = ingestPath & context.Request("f") 
     If File.Exists(filePath) Then 
      File.Delete(filePath) 
     End If 
    End Sub 
    Private Sub ServeFile(ByVal context As HttpContext) 
     If String.IsNullOrEmpty(context.Request("f")) Then 
      ListCurrentFiles(context) 
     Else 
      DeliverFile(context) 
     End If 
    End Sub 

    Private Sub UploadFile(ByVal context As HttpContext) 
     Dim statuses = New List(Of FilesStatus)() 
     Dim headers = context.Request.Headers 

     If String.IsNullOrEmpty(headers("X-File-Name")) Then 
      UploadWholeFile(context, statuses) 
     Else 
      UploadPartialFile(headers("X-File-Name"), context, statuses) 
     End If 


     WriteJsonIframeSafe(context, statuses) 
    End Sub 

    Private Sub UploadPartialFile(ByVal fileName As String, ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus)) 
     If context.Request.Files.Count <> 1 Then 
      Throw New HttpRequestValidationException("Attempt to upload chunked file containing more than one fragment per request") 
     End If 
     Dim inputStream = context.Request.Files(0).InputStream 
     Dim fullName = ingestPath & Path.GetFileName(fileName) 

     Using fs = New FileStream(fullName, FileMode.Append, FileAccess.Write) 
      Dim buffer = New Byte(1023) {} 

      Dim l = inputStream.Read(buffer, 0, 1024) 
      Do While l > 0 
       fs.Write(buffer, 0, l) 
       l = inputStream.Read(buffer, 0, 1024) 
      Loop 
      fs.Flush() 
      fs.Close() 
     End Using 

     statuses.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & fileName, .url = "Upload.ashx?f=" & fileName, .name = fileName, .size = CInt((New FileInfo(fullName)).Length), .type = "image/png", .delete_url = "Upload.ashx?f=" & fileName, .delete_type = "DELETE", .progress = "1.0"}) 

    End Sub 

    Private Sub UploadWholeFile(ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus)) 
     For i As Integer = 0 To context.Request.Files.Count - 1 
      Dim file = context.Request.Files(i) 
      file.SaveAs(ingestPath & Path.GetFileName(file.FileName)) 
      Thread.Sleep(1000) 
      Dim fname = Path.GetFileName(file.FileName) 
      statuses.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & fname, .url = "Upload.ashx?f=" & fname, .name = fname, .size = file.ContentLength, .type = "image/png", .delete_url = "Upload.ashx?f=" & fname, .delete_type = "DELETE", .progress = "1.0"}) 
     Next i 
    End Sub 

    Private Sub WriteJsonIframeSafe(ByVal context As HttpContext, ByVal statuses As List(Of FilesStatus)) 
     context.Response.AddHeader("Vary", "Accept") 
     Try 
      If context.Request("HTTP_ACCEPT").Contains("application/json") Then 
       context.Response.ContentType = "application/json" 
      Else 
       context.Response.ContentType = "text/plain" 
      End If 
     Catch 
      context.Response.ContentType = "text/plain" 
     End Try 

     Dim jsonObj = js.Serialize(statuses.ToArray()) 
     context.Response.Write(jsonObj) 
    End Sub 
    Private Sub DeliverFile(ByVal context As HttpContext) 
     Dim filePath = ingestPath & context.Request("f") 
     If File.Exists(filePath) Then 
      context.Response.ContentType = "application/octet-stream" 
      context.Response.WriteFile(filePath) 
      context.Response.AddHeader("Content-Disposition", "attachment, filename=""" & context.Request("f") & """") 
     Else 
      context.Response.StatusCode = 404 
     End If 
    End Sub 
    Private Sub ListCurrentFiles(ByVal context As HttpContext) 
     Dim files = New List(Of FilesStatus)() 

     Dim names = Directory.GetFiles(context.Server.MapPath("~/UploadedImages/"), "*", SearchOption.TopDirectoryOnly) 

     For Each name In names 
      Dim f = New FileInfo(name) 
      files.Add(New FilesStatus With {.thumbnail_url = "Thumbnail.ashx?f=" & f.Name, .url = "Upload.ashx?f=" & f.Name, .name = f.Name, .size = CInt(f.Length), .type = "image/png", .delete_url = "Upload.ashx?f=" & f.Name, .delete_type = "DELETE"}) 
     Next name 

     context.Response.AddHeader("Content-Disposition", "inline, filename=""files.json""") 
     Dim jsonObj = js.Serialize(files.ToArray()) 
     context.Response.Write(jsonObj) 
     context.Response.ContentType = "application/json" 
    End Sub 
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable 
     Get 
      Return False 
     End Get 
    End Property 

End Class 

現在我想通過生成一個隨機字符串添加一個會話變量,並添加上傳的圖片到新創建的隨機字符串。

1.I已經看到了這Question就這樣使用起來System.Web.SessionState.IRequiresSessionState會話以及我怎麼create一個folder與和後做我的圖片文件夾中添加該怎麼辦我accessnormalaspx頁面此會話變量。

2.(或者)更好的方法是在aspx頁面中創建會話變量並將其傳遞給處理程序?如果是的話我該怎麼做?

3.我試圖從我的處理程序中找到控件。是否有可能?如果有人知道如何得到這個,那麼我的問題將得到解決,以便我試圖從m aspx頁面創建會話。

任何人都可以解釋處理這種情況的更好方法。

+2

您應該只使用context.Session,就像在aspx頁面中做的那樣,無論您在哪裏創建或在哪裏使用,只要您在使用前創建;-)對於第三點,我不' t看到你正在談論的控制 – jbl 2012-04-13 16:11:34

+0

「他們強迫我的是什麼'HttpContext'參數?嗯......」答案就在你面前!這就是爲什麼'HttpContext'可用:) – 2012-04-13 17:15:26

回答

3

我完全同意jbl的評論。

  1. 您可以在項目的任何位置使用HttpContext.Current.Session獲取和設置會話。
  2. 無論你在哪裏創建會話。只要確保會話存在,然後再訪問它。
  3. 不知道你到底在問什麼(需要更多的解釋)。

Here is an example,我在HttpHandler上使用會話。但是,它是在C#(希望你能理解)。

+0

希望沒關係,我無法理解C#,所以我轉換了你的代碼並在這裏發佈。如果它不是我可以刪除它。 – sayth 2012-08-27 06:46:18

0

這不是一個真正的答案,但@Knvn寫了一個C#的例子,我不明白所以我用轉換器將其轉換爲VB。張貼它在這裏,以防將來幫助別人。

Public Class HttpHandler 
    Implements IHttpHandler 
    Implements IRequiresSessionState 
    Public Sub New() 
    End Sub 

    Public Sub ProcessRequest(context As HttpContext) 
     Dim Request As HttpRequest = context.Request 
     Dim Response As HttpResponse = context.Response 

     If SessionHandler.Current.UserID = 0 Then 
      Response.Redirect("~/Default.aspx") 
     Else 
      Try 
       If Request.Path.EndsWith(".pdf") Then 
        Dim client As New WebClient() 
        Dim buffer As [Byte]() = client.DownloadData(HttpContext.Current.Server.MapPath(Request.Path)) 
        Response.ContentType = "application/pdf" 
        Response.AddHeader("content-length", buffer.Length.ToString()) 
        Response.BinaryWrite(buffer) 
       Else 
        Using reader As New StreamReader(HttpContext.Current.Server.MapPath(Request.Path)) 
         Response.Write(reader.ReadToEnd()) 
        End Using 
       End If 
      Catch 
       Response.Redirect("~/Default.aspx") 
      End Try 
     End If 
    End Sub 

    Public ReadOnly Property IsReusable() As Boolean 
     ' To enable pooling, return true here. 
     ' This keeps the handler in memory. 
     Get 
      Return False 
     End Get 
    End Property 
End Class 
+0

不錯,謝謝:-) – NaveenBhat 2012-08-27 08:24:24