开发者

Viewing file using 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 ad开发者_Go百科vise.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜