What is the best way to implement, from a web page a download action using asp.net 2.0?
Log files for a action are created in a directory called [Application Root]/Logs. I have the full path and want to provide a button, that when clicked will download the log file from the IIS server to the users local pc.
Does this help:
http://www.west-wind.com/weblog/posts/76293.aspx
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition","attachment; filename=logfile.txt");
Response.TransmitFile( Server.MapPath("~/logfile.txt") );
Response.End();
Response.TransmitFile is the accepted way of sending large files, instead of Response.WriteFile.
http://forums.asp.net/p/1481083/3457332.aspx
string filename = #"Specify the file path in the server over here....";
FileInfo fileInfo = new FileInfo(filename);
if (fileInfo.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Flush();
Response.TransmitFile(fileInfo.FullName);
Response.End();
}
Update:
The initial code
Response.AddHeader("Content-Disposition", "inline;attachment; filename=" + fileInfo.Name);
has "inline;attachment" i.e. two values for Content Disposition.
Don't know when exactly it started, but in Firefox only the proper file name was not appearing. The file download box appears with the name of the webpage and its extension (pagename.aspx). After download, if you rename it back to the actual name; file opens successfully.
As per this page, it operates on First Come First Served basis. Changing the value to attachment only solved the issue.
PS: I am not sure if this is the best practice but the issue is resolved.
Related
I'm trying to output a CSV file to the client. When the save dialog comes up ( in both Internet Explorer 10 & Google Chrome ) and I try to open it from the browser, the file hangs and is stuck in "Running Security Scan". However, I am able to save the file without an problems. Below is the code I'm using to generate the file. Also to note, I have tried HttpContext.Current.Response.End(); and HttpContext.Current.ApplicationInstance.CompleteRequest(); and got the same result. Please help
string attachment = "attachment; filename=" + "MyCSVFile.csv";
var response = HttpContext.Current.Response;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.AddHeader("content-disposition", attachment);
response.ContentType = "text/csv";
var csv = new StringBuilder();
// ... Build contents for csv file
response.Write(csv.ToString());
response.End();
Apparently, the issue had nothing to do with my code but rather a corrupt file in Windows. I fixed this by opening command prompt with Run as Administrator and running the command sfc/scannow. It now downloads and opens correctly.
In our application, we allow user to upload documents which can be PDF, Doc, XLS, TXT. Uploaded documents will be saved on web server. We need to display link for each document user uploaded and when user click on that link, it should open relevant document. it is expected to have required software to open relevant documents.
To upload document, we use saveAs method of FileUpload control and it works absolutely fine.
Now, how to view it?
I believe, i need to copy/download file to local user machine and need to open it using Process.Start.
For that i need to find user local temp directory. if i put path.GetTempPath(), it gives me web server directory and copy file there.
File.Copy(
sPath + dataReader["url"].ToString(),
Path.GetTempPath() + dataReader["url"].ToString(),
true);
Please advise.
You can't write to the user's drive from the webserver.
What you can do is just provide a link that will download the file to the client.
Set the Content-Disposition header to "attachment" to have a "save as" dialog come up, or to "inline" to let it display in the browser using the registered program from the client.
You can create a LinkButton with a server side handler that contains code like this:
byte[] data = ...; // get the data from database or whatever
Response.Clear(); // no contents of the aspx file needed
Response.CacheControl = "private";
Response.ContentType = "application/pdf"; // or whatever the mimetype of your file is
Response.AppendHeader("Content-Disposition", "attachment;filename=statistic.pdf");
Response.AppendHeader("Content-Length", data.Length.ToString(CultureInfo.InvariantCulture));
Response.BinaryWrite(data);
Response.End(); // no further processing of the page needed
Can you not just put a link on the page pointing to the directory that the files are in?
e.g.
<a href=downloadedfiles/filename.pdf> click here </a>
Once you've provided the link, your job is done. Mostly. The client's browser will handle loading the file when the link is clicked, if it can handle the file type based on the file extension.
I prefer to use a http handler for referencing file links on a web page. This will be important on the day when you need to implement security for uploaded file access; otherwise, any user could access any file.
You don't have to download the file to user machine.
// For pdf documents
Response.Clear();
string filePath = "File path on the web server";
Response.ContentType = "application/pdf"; // for pdf
Response.WriteFile(filePath);
// For word documents
Response.Clear();
string filePath = "File path on the web server";
Response.ContentType = "application/msword";
Response.WriteFile(filePath);
// similarly other file types
I've some files stored in a SQL database. When a user visits a url with the given ID, the BLOB data is retrieved from the database to the webbrower via:
Byte[] myData = b.BlobContent;
Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.AddHeader("Content-Length", b.SizeInBytes.ToString());
Response.BinaryWrite(myData);
Response.End();
However, the iPhone (Safari) can't download a *.txt and *.doc file. It says: "Safari can't download this file". A pdf can(!) be downloaded and viewed.
On Android none of the files can be downloaded.
Is this because the iPhone and Android just can't handle all files? Or am I doing something wrong in the Response.
The content type of application/octent-stream is not appropriate for .txt and .doc files. for .txt you want to use "text/plain" and .doc files you want "application/msword" I suggest that you store the Content-Type value in your database. Here is a good reference for mime types. If you are accepting the files through the FileUpload control the PostedFile object should tell you the contentn type.
EDIT 1: Also, you should not need to set the content-length, as ASP.Net will do this for you.
I have a website which allows secure (ssl) file uploads and download. The site runs on a Window 2003 server with IIS 6.0; asp.net 2.
When using this code:
protected void StartDownLoad(string filename)
{
Response.Clear();
if(filename.EndsWith("zip"))
Response.ContentType = "application/zip";
else
Response.ContentType = "application/msword";
string path = "C:\\Inetpub\\sites\\testsite\\secureDocs\\" + filename;
Response.WriteFile(path);
string headDesc = "inline;filename=" + filename;
Response.AddHeader("Content-Disposition", headDesc);
Response.End();
}
In my tests a 62MB file downloads without any problem -- a 65MB appear to start the download and then immediately stop. The http error logs have four entries each showing "Connection_Dropped". If I remove permissions from the folder and directly access the file through an https url I am able to download files that exceed 65MB so it doesn't seem like it's an IIS issue. Is there an asp.net setting that restricts the response write? Is it an IIS issue? Has anyone run into this before? Any solutions?
You can try using
Response.TransmitFile(path)
instead of
Response.WriteFile(path)
TransmitFile() doesn't buffer the file.
Bye.
After building a filepath (path, below) in a string (I am aware of Path in System.IO, but am using someone else's code and do not have the opportunity to refactor it to use Path). I am using a FileStream to deliver the file to the user (see below):
FileStream myStream = new FileStream(path, FileMode.Open, FileAccess.Read);
long fileSize = myStream.Length;
byte[] Buffer = new byte[(int)fileSize + 1];
myStream.Read(Buffer, 0, (int)myStream.Length);
myStream.Close();
Response.ContentType = "application/csv";
Response.AddHeader("content-disposition", "attachment; filename=" + filename);
Response.BinaryWrite(Buffer);
Response.Flush();
Response.End();
I have seen from: ASP.NET How To Stream File To User reasons to avoid use of Response.End() and Response.Close().
I have also seen several articles about different ways to transmit files and have diagnosed and found a solution to the problem (https and http headers) with a colleague.
However, the error message that was being displayed was not about access to the file at path, but the aspx file.
Edit: Error message is:
Internet Explorer cannot download MyPage.aspx from server.domain.tld
Internet Explorer was not able to open this Internet site. The requested site is either unavailable or cannot be found. Please try again later.
(page name and address anonymised)
Why is this? Is it due to the contents of the file coming from the HTTP response .Flush() method rather than a file being accessed at its address?
Even though you are sending a file, it is the "page" that contains the header information that describes the file you are sending. The browser still has to download that page, then sees the "attachment; filename=" and gives you the file instead.
So if there is an error, it will be page that is shown as the problem. It's a bit like getting a corrupted email with an attachment, you seen the problem in the email not the attachment itself.
Don't call Response.End();