制作动态生成的文件可供下载 [英] Making a dynamically generated file available for download
问题描述
我的目标是采取一些表单输入,并提示用户一旦点击某个按钮即可下载所有内容的摘要。一旦下载文件,我就不需要这个文件,所以我想要一个解决方案,直接将数据直接传输给用户。我目前的解决方案甚至不能提示用户进行下载。任何人都可以指出我在做错什么?
我把它包装成一个web方法,所以我需要添加一个_Default页面类的定义,所以我可以访问某些东西。
公共共享子保存文本(ByVal Text As String)
Dim d As New _Default
Dim FileName As String = System.IO.Path.GetRandomFileName()
使用sw作为新的System.IO.StreamWriter(d.Server.MapPath(FileName +.txt))
sw.WriteLine(Text)
sw.Close()
结束使用
Dim fs As System.IO.FileStream = Nothing
fs = System.IO.File.Open(d.Server.MapPath(FileName +.txt),System.IO.FileMode.Open)
Dim btFile(fs.Length)As Byte
fs.Read(btFile,0,fs.Length)
fs.Close()
With HttpContext.Current.Response
.AddHeader(Content-disposition attachment; filename = output.txt)
.AddHeader(Content-Length,btFile.Length.ToString)
.ContentType =application / octet-stream
.BinaryWrite(btFile)
.End()
End with
End Sub
对不起,以前没有提到,但Webmethod正在被AJAX请求调用!
而不是写入文件系统,请使用 MemoryStream
来保存数据库中的数据,或者更好的是直接写入 Response.OutputStream
。 p>
Content-Disposition
标题似乎是正确的,但是文本文件的正确的MIME类型(ContentType) text / plain
。
My goal is to take some form inputs and prompt the user to download a summary of everything once a certain button is clicked. I have no need for the file once it is downloaded and so I'd like to have a solution where the data is streamed directly to the user. My current solution doesn't even prompt the user for a download. Can anyone point out what I'm doing wrong?
I've got it wrapped as a webmethod and so I needed to add a definition of the _Default page class so I could access certain things.
Public Shared Sub SaveText(ByVal Text As String)
Dim d As New _Default
Dim FileName As String = System.IO.Path.GetRandomFileName()
Using sw As New System.IO.StreamWriter(d.Server.MapPath(FileName + ".txt"))
sw.WriteLine(Text)
sw.Close()
End Using
Dim fs As System.IO.FileStream = Nothing
fs = System.IO.File.Open(d.Server.MapPath(FileName + ".txt"), System.IO.FileMode.Open)
Dim btFile(fs.Length) As Byte
fs.Read(btFile, 0, fs.Length)
fs.Close()
With HttpContext.Current.Response
.AddHeader("Content-disposition", "attachment;filename=output.txt")
.AddHeader("Content-Length", btFile.Length.ToString)
.ContentType = "application/octet-stream"
.BinaryWrite(btFile)
.End()
End With
End Sub
Sorry this wasn't mentioned earlier but the webmethod is being called by an AJAX request!
Instead of writing to the filesystem, use a MemoryStream
to hold the data from the database, or better yet, write directly to the Response.OutputStream
.
The Content-Disposition
header appears to be right, however, the correct mime-type (ContentType) for text files is text/plain
.
这篇关于制作动态生成的文件可供下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!