Radu
Radu

Reputation: 8699

Making a dynamically generated file available for download

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!

Upvotes: 1

Views: 3173

Answers (2)

citronas
citronas

Reputation: 19365

Sounds like a generic handler (*.ashx) file would fit perfectly here

Upvotes: 0

Oded
Oded

Reputation: 499212

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.

Upvotes: 4

Related Questions