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.
Related
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.
I am developing a KnoweldgeBase/Library in which a page lists PDF's and Word Documents associated with the topic selected. These files are uploaded into a folder the URL being "/Interface/AdminUploads/Miscellaneous/FILENAME".
I am listing the files via a table in which each row has an image of the file type, then the file title and then the date published (all created via another page). How can i have the PDF or Word documents opening when i click on the image for the document?
Try This Code.
string filepath ="/Interface/AdminUploads/Miscellaneous/FILENAME"; // Full Path of Pdf.
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(filepath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
Response.Flush();
Response.End();
You need to put the path in the url of the file.
You need to provide the full path you can ur Server.MapPath to get the full path.
Some useful links
How to open a file by clicking on HyperLink
Try the simple code
Response.Write(string.Format("<script>window.open('{0}','_blank');</script>", "pdflocation/" + "Example.pdf"));
I got it to work via...
System.Diagnostics.Process.Start(#fileLocation);
Running this code in a method on image click and passing in the variable 'fileLocation';
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.
I have to give one option in my website to upload multiple files and then allowing users to download those files.
I have done uploading multiple files part, however I am not much clear how I will do downloading part.
I first thought to add hyperlinks dynamically to a label for each file (as I am not sure how many files user will upload).
But then it opens file in browser and does not give option to save or open file.
Main issue is user can submit any type of file like ms doc or xls or text files etc Hence content type is not fixed.
I am not clear on how exactly I will do it I mean adding link buttons dynamically or adding hyperlinks dynamically. And after that how will I download file? I am not able to do
Response.WriteFile(Server.MapPath(#"~/logo_large.gif"));
as content type is not clear.
Please help me regarding code for download all types of files
for download the file:
public void DownLoad(string FName)
{
string path = FName;
System.IO.FileInfo file = new System.IO.FileInfo(path);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
Response.Write("This file does not exist.");
}
}
but this is for word doc/docx files. in the line: Response.ContentType = "application/octet-stream"; you have to define the type of the file.
for displaying hyperlink dynamically write a loop and go over all the files which were uploaded by the user and writh the following code:
yourdivId += "<a href='" + file.FullName + "' >" + file.Name + "</a></br>";
Hope this will help u.()
Response.Clear();
Response.ContentType = YourFile.ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=" + YourFileName);
Response.OutputStream.Write(YourFile, 0, YourFile.Length);
Response.Flush();
Response.End();
I have tried this to download img,txtfile,zip file,doc it works fine..
but little problem user will face that in my case when i opened a word(doc) file its ask
me to openwith..? when i select MsWord it opened it correctly.
For showing these file you can make a grid view to show all file with a download link...
Actually you can follow different ways.
Guide the user during upload and make him specify the file type before starting upload. So the user has to select the content type from a selection. You need to save the correlation between the file and its content type.
Create a map between file extensions and mime-types (See here for example). You need to obtain the file extension and save the correlation between that file and its content type.
Try to identify the content type automatically. There is a Windows
API that let you identify the Mime Type of a file. And here is some code.
After that, you can use st mnmn solution.
You can do it like this:
try
{
string strURL=txtFileName.Text;
WebClient req=new WebClient();
HttpResponse response = HttpContext.Current.Response;
response.Clear();
response.ClearContent();
response.ClearHeaders();
response.Buffer= true;
response.AddHeader("Content-Disposition","attachment;filename=\"" + Server.MapPath(strURL) + "\"");
byte[] data=req.DownloadData(Server.MapPath(strURL));
response.BinaryWrite(data);
response.End();
}
catch(Exception ex)
{
}
You'll have to set few response headers before server sends the file to client. See How to Download a file with a hyperlink
I have read some past posts here on how to download a Excel file from a website. So, I have setup the below code:
string path = MapPath(fname);
string name = Path.GetFileName(path);
string ext = Path.GetExtension(path);
string type = "application/vnd.ms-excel";
if (forceDownload)
{
Response.AppendHeader("content-disposition",
"attachment; filename=" + name);
}
if (type != "")
{
Response.ContentType = type;
Response.WriteFile(path);
Response.End();
}
However, I get no download dialog box.
I try this both in IE 8 and FireFox 10.0.2.
The file is there, it's not locked, and it's not set to read only.
I'm not sure were I went wrong.
According to this link, you need to add this line:
strFileName = Path.GetFileName(path);
Response.TransmitFile( Server.MapPath(strFileName) );
This will cause a Open / Save As dialog box to pop up with the filename of SailBig.jpg as the default filename preset.
This of course assumes you're feeding a file that already exists. If you need to feed dynamically generated - say an image [or any file] that was generated in memory - you can use Response.BinaryWrite() to stream a byte array or write the output directly in Response.OutputStream.
EDIT:
Microsoft's MSDN site has a detailed explanation about File Downloading. It includes both samples for Java and .Net applications, the concept is the same:
Get the response.
With the response:
Set the content type to "APPLICATION/OCTET-STREAM" (it means there's no application to open the file).
Set the header to "Content-Disposition", "attachment; filename=\"" + + "\"".
Write the file content into the response.
Close the response.
So, looking at the MSDN ASP.Net file download, you're lacking the 2.3 step. You're just writing the file name to the response.
// transfer the file byte-by-byte to the response object
System.IO.FileInfo fileToDownload = new
System.IO.FileInfo("C:\\downloadJSP\\DownloadConv\\myFile.txt");
Response.Flush();
Response.WriteFile(fileToDownload.FullName);
With this example you will download your file successfully, of course if you can get the file with no problems :).
EDIT 2:
The HTML component used to download any file must be a regular HTML Request. Any ajax request to download a file won't work. Microsoft explains that here. And the main quote:
Its impossible to attach an event before and after a download through javascript. Browser doesn't allow this type of events for security reasons.
You need to send this before the file attachment header:
Response.ContentType = "application/vnd.ms-excel"
See: Export data to excel file from Classic ASP failing
Try adding such HTTP headers
Content-Type: application/force-download
Content-Type: application/vnd.ms-excel
Content-Type: application/download