File Download inside iframe - asp.net

I'm using following method to download a file.on a button click inside a iframe.it's working fine in every browser except IE.can some one plz suggest me a sollution
private void DownloadToBrowser(string filePath)
{
try
{
FileInfo file = new FileInfo(filePath);
Context.Response.Clear();
Context.Response.ClearHeaders();
Context.Response.ClearContent();
Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Context.Response.AddHeader("Content-Length", file.Length.ToString());
Context.Response.ContentType = "text/plain";
Context.Response.Flush();
Context.Response.TransmitFile(file.FullName);
Context.Response.End();
}
catch (Exception ex)
{
throw ex;
}
}

I would suggest removing the Context.Response.Flush(); line... I don't think it's necessary (as it will happen as part of Context.Response.End(); line), and maybe messing up how the browser receives the file on the next line.
Also, is the file you're transmitting definitely a plain-text file? If not, you'll need to provide a different Context.Response.ContentType();

You have most probably missed some HTTP response headers required by IE.
There is KB on microsoft web.
Also take a look at similar question on SO : PHP script to download file not working in IE

You could try something like this :
Context.Response.Buffer = true;
Context.Response.ContentType = "application/pdf";
Context.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName );
Context.Response.OutputStream.Write(dataBytes ,0,FileContentLength);
Also try adding this to your aspx page :
<%# Page aspCompat="True" other attributes %>

For Understanding I m using Dataset,
For download as a Excel File
Use Namespace:
using System.IO;
using System.Data;
DataSet ds = new DataSet("Table");
ds.Tables.Add("Table1");
ds.Tables[0].Columns.Add("Field1");
ds.Tables[0].Columns.Add("Field2");
ds.Tables[0].Columns.Add("Field3");
ds.Tables[0].Rows.Add();
ds.Tables[0].Rows[0][0] = "1";
ds.Tables[0].Rows[0][1] = "2";
ds.Tables[0].Rows[0][2] = "3";
HttpResponse response = HttpContext.Current.Response;
// first let's clean up the response.object
response.Clear();
response.Charset = "";
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment;filename=sample.xls");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = ds.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
response.Write(sw.ToString());
response.End();
}
}
For Download as a Word File
Replace
response.ContentType = "application/msword";
response.AddHeader("Content-Disposition", "attachment;filename=sample.doc");

Related

ASP.net download file Using HttpContext.Current.Response.TransmitFile in ASP.NET

public void Downloadfile(string sFileName, string sFilePath)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
String Header = "Attachment; Filename=" + sFileName;
HttpContext.Current.Response.AppendHeader("Content-Disposition", Header);
HttpContext.Current.Response.AppendHeader("Cache-Control", "no-cache");
System.IO.FileInfo Dfile = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(sFilePath));
HttpContext.Current.Response.TransmitFile(Dfile.FullName);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
I have a download button, the click will return the call and download the corresponding file download, but sometimes file returns is detailt.aspx file. I do not understand what is happening.
I need help. Thanks a lot
This has worked for me with out issue for a while now.
public void Downloadfile(string sFileName, string sFilePath)
{
var file = new System.IO.FileInfo(sFilePath);
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + sFileName);
Response.AddHeader("Content-Length", file.Length.ToString(CultureInfo.InvariantCulture));
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}

Export to Excel not working in IIS

I am generating excel file and it working fine in local host but not working in IIS.I have a model pop up from where i open pop up window using window.open method where following code is written to generate excel file.
public void GenerateExcelFile(DataTable dt)
{
Response.Clear();
Response.Buffer = true;
string filename = "abc.xls";
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment; filename=" + filename);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView gv = new GridView();
gv.AutoGenerateColumns = true;
gv.DataSource = dt;
gv.DataBind();
gv.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
Please help me to resolve issue.
Recently we where trying to do this, we ended up using this lovely little library: EPPlus
It made the whole process of making our sheets very easy, clean and efficient. Hopefully it will provide a solution to your problem.

How to download a generated excel file from your asp.net application

I am building an asp.net website and I am constructing a Excel document based on some gridview data. I am using Microsoft.Office.Interop.Excel to construct it. I have tried to use a saveFileDialog box using System.Windows.Forms. Through my research online, I have learned that you can’t actually do this in an asp.net application? Everything works great in debugging mode, but when uploading it to the site, the page doesn't work at all. So my man question is, is it possible to to use a saveFileDialog box for an asp.net application? Does anyone know a good workaround for this? I will post my code that works great in debugging mode, but doesn't work when I upload it to my site. Thanks in advance for any help.
using System.Threading;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
public void someEvent()
{
var t = new Thread(SaveFolder);
t.IsBackground = true;
t.SetApartmentState(ApartmentState.STA);
t.Start();
}
public void SaveFolder()
{
saveFileDialog1.Filter = "Sources (*.xls, *.xlsx)|*.xls*;*.xlsx";
saveFileDialog1.ShowDialog();
exportReport();
}
public void exportReport()
{
xlWorkBook.SaveAs(#saveFileDialog1.FileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
releaseObject(xlApp);
releaseObject(xlWorkBook);
releaseObject(xlWorkSheet);
}
public void releaseObject(object obj)
{
try
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
obj = null;
}
catch (Exception ex)
{
obj = null;
MessageBox.Show("Unable to release the Object " + ex.ToString());
}
finally
{
GC.Collect();
}
}
You can't do what you want to with the save dialog. You should just save the file to a temporary location on your server. Once you have the file saved somewhere, you can force the file at the user for download. I usually follow this code (seems to work in all browsers the most consistently). You have to supply the filename and yourFileByteArray variables.
Response.Buffer = true;
Response.Clear();
Response.ClearHeaders();
Response.ContentType = "application/vnd.ms-excel";
Response.CacheControl = "public";
Response.AddHeader("Pragma", "public");
Response.AddHeader("Expires", "0");
Response.AddHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
Response.AddHeader("Content-Description", "Excel File Download");
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
Response.BinaryWrite(yourFileByteArray);
Response.Flush();
Response.End();
There are several ways to get your file as a byte array, but I'll leave that as an exercise for you.
Don't use Interop. Suggest using a mix of HtmlTextWriter, StringWriter, and your GridView.
public void GridViewToExcel()
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=MyFile.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
var writer = new System.IO.StringWriter();
var htmlWriter = new HtmlTextWriter(writer);
GridView1.RenderControl(htmlWriter);
Response.Write(writer.ToString());
Response.End();
}
You can't show a dialog box on the server. There's nobody there to see it. Get rid of the whole saveFileDialog object and just call SaveAs with a generated filename in the server's file system that is guaranteed to be unique. Then transmit that file to your user.

How to export an mschart chart to excel?

I have created a chart with Mschart.I want to export the created chart to excel.
I'm using following code but when I open it in excel I just see some unknown code instead of chart.
using (var chartimage = new MemoryStream())
{
ChartAmalkerd.SaveImage(chartimage, ChartImageFormat.Png);
ExportToExcel(chartimage.GetBuffer());
}
private void ExportToExcel(byte[] input)
{
string attachment = "attachment; filename=Employee.xls";
Response.ClearContent();
Response.ContentEncoding = Encoding.GetEncoding(1256);
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/vnd.ms-excel";
Response.Buffer = true;
this.EnableViewState = false;
Response.BinaryWrite(input);
Response.Flush();
Response.Close();
Response.End();
}
I have found the same issue and after making several attempts, I was able to find out the correct way. This worked for me and the code is as follows.
string tmpChartName = "test2.jpg";
string imgPath = HttpContext.Current.Request.PhysicalApplicationPath + tmpChartName;
Chart1.SaveImage(imgPath);
string imgPath2 = Request.Url.GetLeftPart(UriPartial.Authority) + VirtualPathUtility.ToAbsolute("~/" + tmpChartName);
Response.Clear();
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment; filename=test.xls;");
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
string headerTable = #"<Table><tr><td><img src='" + imgPath2 + #"' \></td></tr></Table>";
Response.Write(headerTable);
Response.Write(stringWrite.ToString());
Response.End();
Hope this helps.
I also came across such scenario in one of my project.
Here is the solution.
http://haseet.blogspot.in/2013/02/develop-chart-in-aspnet-with-export-to-excel-pdf-msoffice-openoffice.html
Add this code for your globalization, this works for me.
Dim info As System.Globalization.CultureInfo = New System.Globalization.CultureInfo("en-US")
Thread.CurrentThread.CurrentCulture = info
Thread.CurrentThread.CurrentUICulture = info
context.Response.ContentEncoding = System.Text.Encoding.UTF8
context.Response.HeaderEncoding = System.Text.Encoding.UTF8

How can I prompt a user to open or save a PDF file returned by a .aspx file?

I have a Flex application that calls a .aspx page on our webserver, which builds a PDF or Excel File. Right now, I am using navigateToURL() to call the file, and this works fine when the output file is built successfully. However, if there is an error, or timeout, there is no way of knowing this in the Flash movie.
I am trying to use URLLoader instead, so that I can listen for an HTTP Status Code, and know when the load is complete, however, the URLLoader simply returns the bitmap data, with nothing prompting the user to open or save the output file. Is there anyway to do this?
Here are both versions of my ActionScript code:
private function buildFile():void
{
var variables:URLVariables = new URLVariables();
variables.rptName = "report1";
variables.rptFormat = "PDF";
var request:URLRequest = new URLRequest();
request.url = "/buildFile.aspx";
request.method = URLRequestMethod.POST;
request.data = variables;
var loader:URLLoader = new URLLoader();
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS,
httpStatusHandler);
loader.load(request);
}
private function buildFile():void
{
var variables:URLVariables = new URLVariables();
variables.rptName = "report1";
variables.rptFormat = "PDF";
var request:URLRequest = new URLRequest();
request.url = "/buildFile.aspx";
request.method = URLRequestMethod.POST;
request.data = variables;
navigateToURL(request, "_self");
}
FYI, here is the block of code that currently outputs the PDF or Excel file:
System.Web.HttpContext httpC;
httpC = System.Web.HttpContext.Current;
httpC.Response.Clear();
httpC.Response.ClearHeaders();
httpC.Response.Expires = 0;
switch (ReportFormat)
{
case "Excel": Response.ContentType = "application/vnd.ms-excel"; break;
case "PDF": Response.ContentType = "application/pdf"; ; break;
}
Response.AddHeader("Content-disposition", "attachment;filename=" + fileName);
BinaryWriter binaryWriter = new BinaryWriter(httpC.Response.OutputStream);
binaryWriter.Write(result);
You server should send "application/octet-stream" header when user requests that PSD file.
With ASP.NET it could look like this:
Response.ClearContent();
Response.ClearHeaders();
// with this header user will be promted to open or download file
Response.ContentType = "application/octet-stream";
// with this header, you will suggest to save file with "test.pdf" name
Response.AddHeader("Content-Disposition", "attachment; filename=test.pdf");
Response.WriteFile(Server.MapPath("~/test.pdf"));
Response.Flush();
Response.Close();
Also take a look here: Downloading files in Flex using the FileReference class
Also set the content-disposition to "attachment" in the aspx page.

Resources