我有一个简单的网页,可以生成一个CSV文件,我希望用户能够在创建完成后下载该文件。
以下是我的情况摘要:
以下是我发送包含PDF文件的.zip的代码:
Protected Sub SaveReportsButton_Click(sender As Object, e As EventArgs) Handles SaveReportsButton.Click
'' The .zip file is created elsewhere
Dim fullPath As String = Server.MapPath("~/Reports/" & Session.SessionID & ".zip")
Response.ContentType = "APPLICATION/OCTET-STREAM"
Dim fileToDownload As New FileInfo(fullPath)
Dim disHeader As String = "Attachment; Filename=""Reports.zip"""
Response.AppendHeader("Content-Disposition", disHeader)
Response.Flush()
Response.WriteFile(fileToDownload.FullName)
End Sub
以下是我正在尝试传输CSV文件的代码:
Protected Sub saveButton_Click(sender As Object, e As System.EventArgs) Handles SaveOutput.Click
Dim list As List(Of String) = {"000000000", "000000000", "000000000"}.ToList()
Dim sb As New Text.StringBuilder
For i As Integer = 0 To list.Count - 1
Dim str As String = list(i)
sb.Append(str)
If i < list.Count - 1 Then
sb.Append(",")
End If
Next
Dim dirPath As String = Server.MapPath("~/Output/" & Session.SessionID)
IO.Directory.CreateDirectory(dirPath)
Dim filePath As String = Server.MapPath("~/Output/" & Session.SessionID & "/Output.csv")
IO.File.WriteAllText(filePath, sb.ToString())
Response.ContentType = "text/csv"
Dim disHeader As String = "Attachment; Filename=""Output.csv"""
Response.AppendHeader("Content-Disposition", disHeader)
Response.Flush()
Response.WriteFile(filePath)
End Sub
就像我说的那样,我希望通过此页面限制创建并留在服务器上的文件,所以我想在完成后删除CSV文件。
任何帮助?
感谢!!!
答案 0 :(得分:1)
使用Response.Write和Response.End
尝试此操作Protected Sub saveButton_Click(sender As Object, e As System.EventArgs) Handles SaveOutput.Click
Dim list As List(Of String) = {"000000000", "000000000", "000000000"}.ToList()
Dim sb As New Text.StringBuilder
For i As Integer = 0 To list.Count - 1
Dim str As String = list(i)
sb.Append(str)
If i < list.Count - 1 Then
sb.Append(",")
End If
Next
Response.Clear()
Response.ContentType = "text/csv"
Dim disHeader As String = "Attachment; Filename=""Output.csv"""
Response.AppendHeader("Content-Disposition", disHeader)
Response.Flush()
Response.Write(sb.ToString())
Response.End()
End Sub
答案 1 :(得分:0)
您根本不需要保存此文件。你为什么不直接回复,就是这样。如果您不创建文件,则无需担心删除它。
内容即时创建。
<强>更新强>
设置响应头“content-disposition”,然后写入Response.OutputStream
在此处了解有关回复标题的详情http://www.jtricks.com/bits/content_disposition.html
就c#代码而言,做类似的事情
Response.AddHeader("content-disposition", string.Format("filename={0}", fileName));
using (var myWriter = new SOMETHING_WHICH_CAN_WRITE_TO_STREAM())
{
myWriter.Write(Response.OutputStream);
}
希望有所帮助