【发布时间】:2019-09-15 07:52:25
【问题描述】:
我正在尝试使用 SharpZipLib 创建 ZIP 文件并将其发送到客户端,在没有网格的页面中代码工作正常并且一切正常,但在有网格的页面中文件总是损坏。
我尝试在 ZIP 文件下载方法的末尾使用 HttpContext.Current.Response.End() 并且它有效,但这意味着 ThreadAbortException 并且之后我无法执行额外的代码
这是我用来创建和下载 ZIP 文件的代码
Public Function ExportToZIPFile(ByVal dataTable As DataTable, orderID As Integer, downloadedZIPFileName As String, ByRef zipFilePassword As String) As Boolean
Dim isSuccess As Boolean = False
Dim excelFilePath As String = Hosting.HostingEnvironment.MapPath("~/Test.xls")
Try
Using streamWriter As StreamWriter = New StreamWriter(excelFilePath)
For i As Integer = 0 To dataTable.Columns.Count - 1
streamWriter.Write(dataTable.Columns(i).ToString().ToUpper() & vbTab)
Next
streamWriter.WriteLine()
For i As Integer = 0 To (dataTable.Rows.Count) - 1
For j As Integer = 0 To dataTable.Columns.Count - 1
If dataTable.Rows(i)(j) IsNot Nothing Then
streamWriter.Write(Convert.ToString(dataTable.Rows(i)(j)) & vbTab)
Else
streamWriter.Write(vbTab)
End If
Next
streamWriter.WriteLine()
Next
streamWriter.Close()
End Using
zipFilePassword = "123456"
SendPasswordInMessage(orderID, zipFilePassword)
HttpContext.Current.Response.ContentType = "application/x-zip-compressed"
HttpContext.Current.Response.AppendHeader("content-disposition", "attachment;filename=" + downloadedZIPFileName + ".zip")
Using zipOutput As ZipOutputStream = New ZipOutputStream(HttpContext.Current.Response.OutputStream)
zipOutput.Password = zipFilePassword
Dim ZipEntry As ZipEntry = New ZipEntry(Path.GetFileName(excelFilePath))
zipOutput.PutNextEntry(ZipEntry)
Using fread = File.OpenRead(excelFilePath)
Dim buffer As Byte() = New Byte(8191) {}
ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(fread, zipOutput, buffer)
End Using
zipOutput.Finish()
End Using
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.End()
isSuccess = True
Catch tah As ThreadAbortException
Catch ex As Exception
MStartLogger.Error(ex, Me.GetType.Name, MethodBase.GetCurrentMethod().Name, "")
Finally
If File.Exists(excelFilePath) Then
File.Delete(excelFilePath)
End If
End Try
Return isSuccess
End Function
我认为问题在于 HttpContext.Current.Response 没有花时间创建文件并下载它,所以我希望创建 ZIP 文件下载它并返回一条成功消息到我以前的代码
【问题讨论】: