chamara
chamara

Reputation: 12709

Open physical file on the server using ASP.NET

I want to open a physical file on the server on HyperLink click.

<asp:HyperLink ID="HyButton1" Target="_blank" NavigateUrl='<%#Eval("FullPath") %>' runat="server" Text="Open File" ></asp:HyperLink>

"FullPath" is like "E:\PINCDOCS\Mydoc.pdf"

Currently in Chrome i'm getting the error.

Not allowed to load local resource:

Can this be done or any other alternative solution?

Upvotes: 3

Views: 13745

Answers (3)

Haitham Shaddad
Haitham Shaddad

Reputation: 4456

When you set the NavigateUrl to FullPath, Chrome will see the link local to the user machine who is accessing the site and not the server itself.

So, you always need to make the URL for any hyberlink to be in the form of //someURL or http://someurl

In your case, you have to remove the NavigateUrl and add a OnClick handler, and inside the handler, you will read the file using the FileStream and write the file contents to the response stream then flush it

example of the click handler:

context.Response.Buffer = false;
context.Response.ContentType = "the file mime type, ex: application/pdf";
string path = "the full path, ex:E:\PINCDOCS";

FileInfo file = new FileInfo(path);
int len = (int)file.Length, bytes;
context.Response.AppendHeader("content-length", len.ToString());
byte[] buffer = new byte[1024];
Stream outStream = context.Response.OutputStream;
using(Stream stream = File.OpenRead(path)) {
    while (len > 0 && (bytes =
        stream.Read(buffer, 0, buffer.Length)) > 0)
    {
        outStream.Write(buffer, 0, bytes);
        len -= bytes;
    }
}

Upvotes: 0

Philip Pittle
Philip Pittle

Reputation: 12295

The physical file should be located within an IIS Web Site, Virtual Directory or Web Application. So you'd need to create a virtual directory to E:\PINCDOCS. See here for instructions: http://support.microsoft.com/kb/172138

Then in your code behind you can use code like: http://geekswithblogs.net/AlsLog/archive/2006/08/03/87032.aspx to get a Url for the physical file.

Upvotes: 2

karthi
karthi

Reputation: 470

//SOURCE
<asp:HyperLink ID="HyButton1" Target="_blank" NavigateUrl='<%#ful_path(Eval("")) %>' runat="server" Text="Open File" ></asp:HyperLink>//ful_path is c# function name

//C#:
protected string ful_path(object ob)
{
    string img = @Request.PhysicalApplicationPath/image/...;
    return img;
}

Upvotes: 0

Related Questions