ASP.NET programmatic file download
So I have a page on which I dynamically generate a table and link buttons all inside a large UpdatePanel. Each link button when clicked will cause this method to be called. The goal is to have the link point to a file in my DB and when clicked allow the user to open/save as that file. This exact method works fine on another page of my site with generally the same setup but on this one I'm getting:
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled. Details: Error parsing near '%PDF-1.3 % 1 0 ob'.
public void downloadFile(int fileID)
{
using (SurveyDataContext context = new SurveyDataContext())
{
try
{
var file = context.tblFiles.Single(f => f.FileID == fileID);
Response.Clear();
Response.Buffer = true;
Response.BufferOutput = true;
Response.ContentType = file.MIMEtype;
Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + file.FileName.Trim() + "\"");
Response.AddHeader开发者_开发技巧("Extension", file.FileName.Substring(
file.FileName.LastIndexOf('.') + 1).ToLower());
Response.BinaryWrite(file.FileData.ToArray());
Response.Flush();
Response.End();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.InnerException);
}
}
}
What am I doing wrong? I'm not doing any Response.Writes or anything. This method is the only that touches Response. Is there some other way I should be doing this?
Do you have an UpdatePanel
or something like it?
If that's your case then you can do this at page load:
ScriptManager _scriptManager = ScriptManager.GetCurrent(this.Page);
_scriptManager.RegisterPostBackControl(Button1);
You should try Response.Flush before Response.End if this doesn't work then you have sample code here at http://dotnetperls.com/response-binarywrite-aspnet
Look here
You probably set bad content type
Does calling Response.Clear();
before everything else clear it up? Otherwise, here's a blog post that goes into some other troubleshooting.
I think the problem is caused by setting both Response.Buffer and Response.BufferOutput. BufferOutput alone is probably what you want.
If removing Response.Buffer doesn't work, I would try simplifying a little bit by setting ContentType = "application/octet-stream" and commenting out the "Extension" header. The extension on the filename alone should be enough for the browser.
I realized what I was doing wrong... I need to make each link button have a PostBackTrigger. Once I did that everything worked the original way I had it.
精彩评论