Ho questo file ashx che uso per il download di files&co: ci arrivo con un href, gli passo due parametri in querystring e lui si prende il file da restituire e me lo passa (un modo come un altro per non mostrare all'utente in chiaro il percorso del file che sta scaricando).
Funziona, nel senso che sto provando a scaricare un file txt, lui lo trova e me lo passa chiedendomi se lo voglio aprire o scaricare, me lo apre (o me lo scarica) ma qui poi succede qualcosa per cui mi esce un'eccezione e nel testo del file trovo accodato "thread interrotto" (che è il message dell'eccezione)....
cosa sbaglio?
codice:
<%@ WebHandler Language="VB" Class="dloader" %>
Public Class dloader : Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim sContentType As String = ""
Dim sezione As Integer = "" & context.Request("w")
Dim nomefile As String = "" & context.Request("fn")
Dim fullpath = ConfigurationManager.AppSettings("repopath") & "\repo" & sezione & "\" & nomefile
fullpath = Replace(fullpath, "\\", "\")
Try
sContentType = System.Web.MimeMapping.GetMimeMapping(nomefile)
Dim bData As Byte()
Dim br As System.IO.BinaryReader = New System.IO.BinaryReader(System.IO.File.OpenRead(fullpath))
bData = br.ReadBytes(br.BaseStream.Length)
SaveDocOutputStreamAttachment(bData, nomefile, sContentType)
Catch ex As Exception
context.Response.ContentType = "text/plain"
context.Response.Write(vbCrLf & "Impossibile restituire il contenuto del file, potrebbe essere corrotto. " & vbCrLf)
context.Response.Write(ex.Message)
End Try
End Sub
'---------------------------------------------------------------------------------------------------------------------------------------------------
'salva buffer di byte nello stream di uscita come attachemt
'---------------------------------------------------------------------------------------------------------------------------------------------------
Public Sub SaveDocOutputStreamAttachment(buffer As Byte(), nomeDocumento As String, Optional contentType As String = "application/octet-stream")
System.Web.HttpContext.Current.Response.Clear()
System.Web.HttpContext.Current.Response.HeaderEncoding = Encoding.Default
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename=""{0}""", nomeDocumento))
System.Web.HttpContext.Current.Response.AddHeader("Content-Length", buffer.Length.ToString)
System.Web.HttpContext.Current.Response.ContentType = contentType
If buffer.Length > 0 Then
'queste due istruzioni sono equivalenti
System.Web.HttpContext.Current.Response.OutputStream.Write(buffer, 0, buffer.Length)
'System.Web.HttpContext.Current.Response.BinaryWrite(buffer)
End If
System.Web.HttpContext.Current.Response.Flush() : System.Web.HttpContext.Current.Response.End()
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class