Download File From Another Sever With Save as Dialogue Box - c#

I want to download a file from another server with save as dialog box... I tried 1 example to download file from our server which worked but i don't know how to work for files which are hosted on another server.
If I try to download then i am getting It is not valid virtual path
Response.WriteFile(Convert.ToString(http://abc.com/sbe/test.pdf));
What should i do to download files from another server.
Regards,

I got this code from a guy in asp.net forums.. His code help me to resolve my issue for a complete discussion check this link out : http://forums.asp.net/p/1772874/4847084.aspx/1?p=True&t=634655765939994111
Below is the code
WebClient client = new WebClient();
string url = #"http://www.agiledeveloper.com/articles/BackgroundWorker.pdf";
byte[] data = client.DownloadData(new Uri(url));
Response.Clear();
Response.ContentType = "application/pdf";
Response.AppendHeader("Content-Disposition", String.Format("attachment; filename={0}", "aspnet.pdf"));
Response.OutputStream.Write(data, 0, data.Length);

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.

.net CSV file stream to browser loosing characters on production server

I've got basic functionality to stream a file to the browser which invokes a "Save As". The output is dynamically generated and stored within a string and not a file saved on the server.
See code below.
string output = GenerateCSVDdata;
Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=\"test.csv\");
Response.ContentType = "application/octet-stream";
Response.BinaryWrite(System.Text.Encoding.UTF8.GetPreamble());
Response.Write(output);
Response.End();
Now, on my development server, the CSV fully downloads. On the production server, the last few characters on end are cut off. The larger the CSV, the more characters are missing. I've tried so many different things like Response.Flush etc but nothing can fix it. The only thing I can do is throw a load of empty chars on the end in hope nothing gets cut.
Is there something quite wrong with this method of streaming a file download without actually saving the file to disk?
Thanks for your help.
Can you determine if there is a difference in the byte count for the .csv file you are using?
byte[] defaultEncodingBytes = System.Text.Encoding.Default.GetBytes(defaultEncodingFileContents);
byte[] UTF8EncodingBytes = System.Text.Encoding.UTF8.GetBytes(defaultEncodingFileContents);
Try this, it worked for me.
void DownloadFile(string filename)
{
//string filename = "c:\\temp\\test.csv";
byte[] contents = System.IO.File.ReadAllBytes(filename);
Response.Clear();
Response.ClearHeaders();
Response.AppendHeader("Content-disposition", String.Format("attachment; filename=\"{0}\"", System.IO.Path.GetFileName(filename)));
Response.AppendHeader("Content-Type", "binary/octet-stream");
Response.AppendHeader("Content-length", contents.Length.ToString());
Response.BinaryWrite(contents);
if (Response.IsClientConnected)
Response.Flush();
}
Regards.

ZIP download contains html content

When I use the following code to download a ZIP file it appears to work. However, when I attempt to open the downloaded ZIP, I get an 'invalid compressed folder' message. When I open the ZIP in notepad I see it is filled with HTML.
string fp = Server.MapPath("directory\\file.zip");
FileInfo file = new FileInfo(fp);
if (file.Exists)
{
Response.ClearContent();
Response.AddHeader("content-disposition","attachment; filename=" + file.Name);
Response.AddHeader("content-length", file.Length.ToString());
Response.ContentType = "application/zip";
Response.TransmitFile(file.FullName);
Response.End();
}
An issue I can't seem to fix that is probably related is when I try to manually type in the address of the file (http://website.com/downloads/file.zip), I get a redirect (http://website.com/login.aspx) even when logged in as the admin. Any pointers in where to look would be greatly appreciated.
Instead of just using Response.ClearContent() also use Response.ClearHeaders() to remove all the current headers as well as the body of the response.
From MSDN, HttpResponse.ClearContent Method:
The ClearContent method does not clear header information.

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.

Creating and saving a text file from a c# ASP.NET app

I want to be able to create a text file and let the user save this to their own PC. Currently i have to do this:
StreamWriter sw;
sw = File.CreateText("C:\\results.txt");
Which obv saves on the web server but how can I replace that string with a link to their own computer? I looked at SaveFileDialog but it seems to only work for Windows Forms and not ASP sites, any advice?
Thanks in advance
You need to tell the Users Browser to Download the file. You can use the following code:
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType="text/plain";
Response.AppendHeader( "content-disposition", "attachment; filename=" + filename );
Response.AppendHeader( "content-length", fileContents.Length );
Response.BinaryWrite( fileContents );
Response.Flush();
Response.End();
Where fileContents is a byte[] of the files contents. and filename is the name of the file to suggest to the user.
You need to write an ASPX (or ASHX) page that sends your data down the wire, and add a Content-Disposition header.
You can stream the file to their browser. Here is a good article.
You need to save the file to a publicly accessible path and then present the user with a link to the file.

Categories