Question

I have uploaded a text file to my database into a Image field. The problem is when I try to retrieve the file (make the user able to download it on a click on a link). When I try to download it, it is simply filled with the content of the webpage (all the html is filled into the text file). I am considering it to be an error with the way I try to download the file. Isn't it possible to stream the content to a file, without first saving it into a temporary file?

The code I am using is shown below. UploadFiles is my class which contains the data, id, name etc.

    public void DownloadUploadedFile(Page sender, UploadFiles uf)
{
    sender.Response.ContentType = uf.FileType; // the binary data
    sender.Response.AddHeader("Content-Disposition", "attachment; filename=" + uf.FileName);
    sender.Response.BinaryWrite(uf.FileData);
}
Was it helpful?

Solution

It sounds like you've got too much of the rest of the page going to the client. You need to clear the response, and close it afterwards; try:

sender.Response.Clear();
sender.Response.ContentType = uf.FileType; // the binary data
sender.Response.AddHeader("Content-Disposition", "attachment; filename="
         + uf.FileName);
sender.Response.BinaryWrite(uf.FileData);
sender.Response.Close();

Alternatively, use a handler (ashx) to do this - since that doesn't include the regular page markup.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top