Viewing file using asp.net - asp.net

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

Related

File Download from web site contains the site's HTML, not the intended data

I am working on an ASP.Net/VB.Net web application in which a file is to be generated and sent to the client when a button on the page is clicked. I have the following code to do this:-
Dim text_file_name As String = WriteOutputFile() ' Generate output file
Response.ClearContent()
Response.Clear()
Response.ContentType = "text/plain"
Response.AddHeader("Content-Disposition", "attachment; filename=" + text_file_name + ";")
Response.Flush()
HttpContext.Current.ApplicationInstance.CompleteRequest()
File.Delete(text_file_name)
This appears to complete and a file is duly downloaded, but on opening it I find it contains the web page HTML, rather than the intended file text. I observe though that the file (extension .csv) is opened up in Excel, so it is getting at least that part of the message.
I have verified that the file is created as intended by leaving out the File.Delete and watching the files accumulate in the server's directory.
In a previous attempt I had
Response.End()
in place of the complete request; this also generated a .csv file, but one containing the details of a thread exception.
Does anyone know what I am doing wrong?
You're sending the intended file name to the browser as a header hint but you aren't actually sending the file itself. To do that, use Response.WriteFile()

Asp.net Download file on mobile platform

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.

Display database resume to user

Im using upload control to upload my resume(word document) in sql server 2005 database.and i can download it from database when i click link button...Its all working file...My problem is how can i show my full resume to user (how to display my resume) from my database?
You need to set the response contenttype header to the correct type and then send the file (I am assuming you have it as a byte array):
Response.Clear();
Response.ContentType = "application/pdf";
Response.BinaryWrite(fileBuffer);
Response.End();
You may also want to add a content-disposition header in order to let the user decide how to open the file:
// This goes after the clear and before the write
Response.AddHeader("content-disposition", string.Format("attachment; {0}", archivedFile.Name));
You may want users of your website to install these plugins which directly opens any document link in Google Docs Viewer. Might be that you can dig into these plugins and get a link so that you can redirect your users on that link and they will not have to install these plug ins
Firefox plug in and Google Chrome Plug In

When downloading a file using FileStream, why does page error message refers to aspx page name, not file name?

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();

How to implement a file download in asp.net

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.

Resources