Using SharePoint 2010 sandbox webpart, I am dynamically making a pdf file in memory. I want to have a download browser prompt after the file is made however I am having issues with HttpContext.Current.Response where it throws the error
System.NullReferenceException: Object reference not set to an instance of an object. at System.Web.HttpApplication.CompleteRequest() at System.Web.HttpResponse.End()
Here is my code
protected override void CreateChildControls() {
Button btnExport = new Button();
btnExport.Text = "Export";
btnExport.Click += new EventHandler(this.btnExport_Click);
this.Controls.Add(btnExport);
}
protected void btnExport_Click(object sender, EventArgs e) {
// shorten code that is making PDF document
saveFileLocal();
}
public void saveFileLocal(){
var Response = HttpContext.Current.Response;
byte[] file = returnPDFBytes();
Response.Clear();
// Clear the content of the response
Response.ClearContent();
Response.ClearHeaders();
// Buffer response so that page is sent after processing is complete.
Response.BufferOutput = true;
// Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.pdf");
// Add the file size into the response header
Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
Response.ContentType = "Application/pdf";
Response.BinaryWrite(file);
Response.Flush();
Response.End();
}
I hope the provided information helps explain as it's very odd to me that this isn't work.
_layouts/download.aspx?SourceURL=LIBRARYURLHEREand then delete it which is very hacky ;/ – user3643344 Jan 30 '15 at 18:57