views:

149

answers:

1

Hi, 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);
}
+2  A: 

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.

Marc Gravell
I have added the .Clear() and the .close(), but now it doesn't request me to save or open the file, and just continues to load forever. I am thinking it is because I am closing the file, before the user have had the option to save it?
Dofs
I found out I should write sender.Respons.Close() and then I didn't get all the html out. But now the file just contains a string "System.Byte[]" and not the actual content?
Dofs
I will make a new thread with the new question.
Dofs