好的,由于显然仅提供一个可工作的示例会被投下反对票,所以让我详细解释一下:
首先,你不需要做
textWriter.Flush()
希望您能够将TextWriter的内容刷新到MemoryStream中。
然后,您不需要执行以下操作:
memoryStream.Position = 0
期望将MemoryStream从位置0开始“写入”。
然后执行
memoryStream.Write(bytesInStream, 0, bytesInStream.Length)
但实际上你的意思是什么。
memoryStream.Read(bytesInStream, 0, CInt(memoryStream.Length))
您还忽略了长度为Long,而read使用整数,因此您可能会遇到异常。
这是您的代码最小化适应“工作”的方式(我将其复制到了一个vb项目中)。
Imports System.Web
Imports System.Web.Services
Public Class TextHandler
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'context.Response.ContentType = "text/plain"
'context.Response.Write("Hello World!")
Dim memoryStream As New System.IO.MemoryStream()
Dim textWriter As System.IO.TextWriter = New System.IO.StreamWriter(memoryStream)
textWriter.WriteLine("Something")
textWriter.Flush()
memoryStream.Position = 0
Dim bytesInStream As Byte() = New Byte(memoryStream.Length - 1) {}
'memoryStream.Write(bytesInStream, 0, bytesInStream.Length)
memoryStream.Read(bytesInStream, 0, CInt(memoryStream.Length))
memoryStream.Close()
context.Response.Clear()
context.Response.ContentType = "application/force-download"
context.Response.AddHeader("content-disposition", "attachment; filename=name_you_file.txt")
context.Response.BinaryWrite(bytesInStream)
context.Response.End()
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
然后您使用:
Content-Type: application/force-download
这意味着,“我这个Web服务器会向您(浏览器)撒谎,告诉您该文件是什么,以便您不会将其视为PDF / Word文档/ MP3 /任何其他类型的文件,并提示用户将神秘文件保存到磁盘。这是一种肮脏的技巧,当客户端不执行“保存到磁盘”操作时,它会出现严重故障。”
...
最后,您未正确编码文件名,因此如果文件名中使用非ASCII字符,则文件名将变得混乱,如果您恰好是中国人或俄罗斯人,并完全在ASCII字符集之外运行,则非常有趣。
原始内容:
这是我一个ajax处理程序的快速摘录。
它是VB.NET,转换时要注意长度-1的事情。
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim strFileName As String = "Umzugsmitteilung.doc"
Dim strUID As String = context.Request.QueryString("ump_uid")
context.Response.Clear()
'If String.IsNullOrEmpty(strUID) Or fileData Is Nothing Then
' context.Response.Write("<script type=""text/javascript"">alert('File does not exist !')</script>")
' context.Response.End()
'End If
context.Response.ClearContent()
'context.Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName)
context.Response.AddHeader("Content-Disposition", GetContentDisposition(strFileName))
'context.Response.ContentType = "application/msword"
context.Response.ContentType = "application/octet-stream"
GetUmzugsMitteilung(strUID)
context.Response.End()
End Sub ' ProcessRequest
Public Shared Sub SaveWordDocumentToOutputStream(strUID As String, doc As Aspose.Words.Document)
Using ms As System.IO.MemoryStream = New System.IO.MemoryStream()
CreateWordDocumentFromTemplate(strUID, doc, ms)
ms.Position = 0
Dim bytes As Byte() = New Byte(ms.Length - 1) {}
ms.Read(bytes, 0, CInt(ms.Length))
System.Web.HttpContext.Current.Response.OutputStream.Write(bytes, 0, ms.Length)
ms.Close()
End Using ' ms
End Sub ' SaveWordDocumentToOutputStream
Public Shared Function StripInvalidPathChars(str As String) As String
If str Is Nothing Then
Return Nothing
End If
Dim strReturnValue As String = ""
Dim strInvalidPathChars As New String(System.IO.Path.GetInvalidPathChars())
Dim bIsValid As Boolean = True
For Each cThisChar As Char In str
bIsValid = True
For Each cInvalid As Char In strInvalidPathChars
If cThisChar = cInvalid Then
bIsValid = False
Exit For
End If
Next cInvalid
If bIsValid Then
strReturnValue += cThisChar
End If
Next cThisChar
Return strReturnValue
End Function ' StripInvalidPathChars
Public Shared Function GetContentDisposition(ByVal strFileName As String) As String
' https://dev59.com/SXVD5IYBdhLWcg3wGHeu
Dim contentDisposition As String
strFileName = StripInvalidPathChars(strFileName)
If System.Web.HttpContext.Current IsNot Nothing AndAlso System.Web.HttpContext.Current.Request.Browser IsNot Nothing Then
If (System.Web.HttpContext.Current.Request.Browser.Browser = "IE" And (System.Web.HttpContext.Current.Request.Browser.Version = "7.0" Or System.Web.HttpContext.Current.Request.Browser.Version = "8.0")) Then
contentDisposition = "attachment; filename=" + Uri.EscapeDataString(strFileName).Replace("'", Uri.HexEscape("'"c))
ElseIf (System.Web.HttpContext.Current.Request.Browser.Browser = "Safari") Then
contentDisposition = "attachment; filename=" + strFileName
Else
contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(strFileName)
End If
Else
contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(strFileName)
End If
Return contentDisposition
End Function ' GetContentDisposition
bytesInStream
的大小是否大于0? - Tieson T.MemoryStream
有一个ToArray
方法,可以给你一个等效的byte[]
数组? - Damien_The_Unbeliever