DNK Gif

Dot Net Knowledge

Labels

Tuesday, 16 June 2015

Save bytearray[] data to HttpResponse object

How to save bytearray[] data to HttpResponse and download the file by browser

Here's the code for this:-

Write this in your Webform.aspx:

<asp:LinkButton ID="LinkButton1" runat="server" OnClick="LinkButton1_Click" >LinkButton1</asp:LinkButton>


and this is the code behind function's code:-

protected  void LinkButton1_Click(object sender, EventArgs e)
        {            
            IReportBuilder builder = new ReportBuilder();
            IReportDataProvider data = new ReportDataProvider();
            IReportProvider report = new ReportProvider(data, builder);
            byte[] buffer = report.GetMyReport(Convert.ToInt32(txtUserId.Text));            
            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
            response.Clear();            
            string filename = "attachment; filename=MyReport_UserId_"+txtUserId.Text;
            response.AddHeader("Content-Type", "application/ms-excel");
            response.AddHeader("Content-Disposition", String.Format(filename+".xlsx; size={0}",buffer.Length.ToString()));
            response.BinaryWrite(buffer);
            response.End();  
}

Note:- Content-Type can be octet-stream, vnd.ms-excel, ms-word or pdf also


Remember:- Where-ever you are creating the bytearray[] file from Memorystream object, seek the file pointer to 0 or beginning by this piece of code.

                MemoryStream stream = new MemoryStream();
                workbook.Save(stream, SaveFormat.Xlsx);
                stream.Seek(0, SeekOrigin.Begin);
                return stream.ToArray();

No comments:

Post a Comment