asp.net-mvc save excel file to specific location - c#

I have the following code that downloads a file to the client's machine and it works great. However, I also need to ask the user where they want to save the file before the download begins.
Is this something I do in the action method (someone in the below code) or is this an option the client has to set on his/her browser and independent of what my code does?
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + fileName + ";");
response.TransmitFile(filePath + fileName);
response.Flush();
response.End();

Yes, "this an option the client has to set on his/her browser and independent of what my code does".

As best I can tell, that is the responsibility/behavior of the browser. If you want more client side control, you would have to write a client side app to save off to a specific location, or (easier) have the end user configure their browser to ask where to save downloads to.

Related

How to show Save As Dialog on ASP.net

I'm newbie on asp.net, i am developing Online Report Generator, i want to let the client to choose where he/she want to put his/her files so this is my code but didn't seems to work, it returning to my ajax error statement my ConfigurationManager.AppSettings["ExtractFolder"] is equal to "c:\temp\": just want to ask what's wrong with the code?
context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AddHeader("content-disposition", "attachment;filename="+filename);
context.Response.WriteFile(ConfigurationManager.AppSettings["ExtractFolder"]+filename);
context.Response.Flush();
context.Response.End();
Try this
String FileName = "FileName.txt";
String FilePath = "C:/...."; //Replace this
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
For more content types check our http://en.wikipedia.org/wiki/MIME_type#List_of_common_media_types
Basically you can't do what you want to do the way you are trying to do it.
The ASP.net code that you have is dependant on being part of a full http Request/Response cycle. The part where it is setting headers is where it telling the browser to download stuff.
An AJAX request is looking for a specific return with its request, generally javascript passable data. You are not returning this but rather the contents of a file.
Here's an article the explains the concepts and problems a little more. It also provides you an alternate solution. Basically the solution revolves around using an iFrame to handle the file download request.
First, check that your source file you want to send to the user is in c:\temp\ and that you have set filename to the name of the file you are sending. Next you will want to make sure that your .net process has permission to c:\temp on your server. It probably doesn't.
Also, make sure you understand that response.writefile actually reads a file from the server and writes it out to the browser. You can't specify where the user saves the file to locally, this is handled by the browser not by your code.
Using Coders sample code make sure you change the following (see my comments)
String FileName = "FileName.xlsx"; //MAKE SURE THIS IS YOUR EXCEL FILENAME ON YOUR SERVER
String FilePath = "C:/...."; //SET THIS TO THE FOLDER THE FILE IS IN (put your file in your root folder of your website for now, you can move it later once you get the download code working)
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; //MAKE SURE YOU HAVE CHANGED THIS TOO
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
I also suggest trying the above in a standalone page first then incorporate it into your AJAX page once you know its working.

Response.Redirect does not work

I have a page that exports large amount of data to excel 2007 macro enabled format. I have Response.Redirect at the end to redirect to another page after the excel file is created but the redirect does not work when I have really large amount of data i.e about 60,000+ rows.
Below is the snippet of the code that I am using to save the excel file:
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=RegionData.xlsm");
Response.ContentType = "application/octet-stream";
wbRegionData.Save(Response.OutputStream);//();
Response.End();
Response.Redirect("RegionData.aspx?PALID=" + AVListID, true);
Thank you for your help.
You cannot do a file download and a redirect in the same server response. If you need to perform a redirect after a successful file download you will need to somehow tell the client that a file download successfully occurred which can only be accomplished by writing a cookie as far as I know.
I have created the jQuery File Download plugin (Demo) (GitHub) (Blog Posts) that simplifies a lot of this stuff, using the plugin your code could be like this:
ASP.NET CODE:
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=RegionData.xlsm");
Response.ContentType = "application/octet-stream";
Response.SetCookie(new HttpCookie("fileDownload", "true"){Path = "/"});
wbRegionData.Save(Response.OutputStream);//();
Response.End();
JavaScript:
$.fileDownload("/urltofiledownload/", {
successCallback: function (url) {
window.location = "/redirecturl/";
}
});
Without more of your code I can't give you a complete solution (look at the Demo for examples) but I think using the plugin would be your easiest and best bet.
You can't because you are closing the response by calling Response.End(); You must have to add define these two actions separately (Download and redirection).
It will not work because the Respose.End() Method stop the normal execution of the page, I have refatored your code and delete de Response.End() Method, now it's work.
Response.Clear();
Response.AppendHeader("content-disposition", "attachment; filename=RegionData.xlsm");
Response.ContentType = "application/octet-stream";
wbRegionData.Save(Response.OutputStream);//();
Response.Redirect("RegionData.aspx?PALID=" + AVListID, true);

Prompt user to save/open file in ASP.NET C#

It shouldn't be this hard to find out how to do this. Basically I'm trying to take a string and let the client save it when they click a button. It should pop up with a Save/Open dialog. No extra bells and whistles or anything. It's not rocket science, (or so I would've thought).
There seems to be a ton of different ways, (StreamWriter, HttpResponse, etc.), but none of the examples I've been able to find work properly or explain what's going on. Thanks in advance.
An example one of the many blocks of code I've found...
(This is just an example, feel free to not base your answer around this.)
String FileName = "FileName.txt";
String FilePath = "C:/...."; //Replace this
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath);
response.Flush();
response.End();
Line 2 says to replace that string. How? This code was advertised as bringing up a dialog. I shouldn't be having to set a path in the code, right?
EDIT: Final Outcome (Edited again, Delete has to come before End();)
string FilePath = Server.MapPath("~/Temp/");
string FileName = "test.txt";
// Creates the file on server
File.WriteAllText(FilePath + FileName, "hello");
// Prompts user to save file
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.ClearContent();
response.Clear();
response.ContentType = "text/plain";
response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");
response.TransmitFile(FilePath + FileName);
response.Flush();
// Deletes the file on server
File.Delete(FilePath + FileName);
response.End();
Line 2 (FilePath) indicates the path to the file on the server
Line 8:
response.TransmitFile(FilePath);
Transmits that specific file to the client and THAT is what pops the save dialog.
If you don't transmit the file, I'm not sure if the dialog will pop up at all (even though you set a header)
Anyways, I think line 8 should read:
response.TransmitFile(FilePath + FileName);
There will be a default dialog box by browser, if it will find Response as some file. If you want browser to display that default dialog box, all you need to do is send response to browser as file, which you can do in number of ways:
If it is a static file,
best way is to just mention path of file in anchor tag's href.(obviously if you don't have security concern)
Just out along with your response, the way it is done in your example.
Other ways you can refer here 4 ways to send pdf from asp.net
If it is a dynamic file which you need to generate at run time, you can do a trick, generate the file from filestream, put it in some temporary folder at server, read it back as a static file as mentioned above.
Just use this code it should work to prompt the user to open a dialog for opening or saving the file on the system ....
byte[] bytesPDF = System.IO.File.ReadAllBytes(#"C:\sample.pdf");
if (bytesPDF != null)
{
Response.AddHeader("content-disposition", "attachment;filename= DownloadSample.pdf");
Response.ContentType = "application/octectstream";
Response.BinaryWrite(bytesPDF);
Response.End();
}
FilePath is supposed to point to the file you want to send to the client. This is the path on the server.

Download file and Notification with Asp.Net

My web application have a download button and when the client click it, it must show a message saying that file was already downloaded.
Here is the code to download:
FileInfo arquivo = new FileInfo(pathCompletoArquivo);
FileInfo fInfo = arquivo;
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + fInfo.Name + "\"");
Response.AddHeader("Content-Length", fInfo.Length.ToString());
Response.WriteFile(fInfo.FullName);
Response.Flush();
I want to show a message to the client after this, I tried popups, javascripts... but nothing would work.
Obs.: Dont need to show the message when the download is concluded.
You cannot do this on the same HTTP response that also sends the file contents back.
What you need to do is add a click handler on the download button that displays a popup if the file has been downloaded, and makes the actual request to download the file (that runs the code you show us) if it has not. You would do that using JavaScript.
Looks like your on the right track. Make sure you check Response.IsClientConnected when writing to the response stream.

Unable to force file download from an asp.net page without getting security bar along top of IE

How can I force the Save As Dialog box to show within an asp.net page without getting the browser bar at the top saying "To help protect security IE blocked this site from downloading files..... Click here for options"
It then forces the user to click the Download File option - but this first time they do this nothing happens.
What I need to happen is that the File Download box should be displayed with the options of saving or opening etc.. the file to download.
The asp.net/C# code I am currently using is:
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=myfilename");
Response.WriteFile(myfilename);
Response.End();
Any ideas why I shouldn't just get the File Download box ?
Try to change the Content Type to "Application/Force-Download" instead
ASP.NET C# Example:
Response.AppendHeader("Content-Type", "application/force-download;");
Fully functional code:
try
{
string FileName = Request.QueryString["file"];
Response.AppendHeader("Content-Type", "application/force-download;");
Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.WriteFile(#Server.MapPath("download/") + "\\" + FileName);
Response.End();
}
catch (Exception)
{
//Handle Error
}

Categories