The right way of setting <a href=""> when it's a local file
Asked Answered
S

8

31

I'm trying to link to a local file. I've set href as follows:

<a href="file://C:/path/to/file/file.html">Link Anchor</a>
  • In Firefox, when I right click and "open link in new tab", nothing happens.

  • When I right click and "copy link location", then manually open a new tab and paste the copied link, it works fine. So it seems my file:// syntax is fine. I've also tried it with 3 slashes like file:/// but it's the same result.

What am I doing wrong?

Slurry answered 18/8, 2012 at 19:53 Comment(2)
I think the problem is with Firefox. As a security feature they prevent remote files from being able to access local files. There are workarounds, but they seem to be implemented through the browser. More information can be found here: kb.mozillazine.org/Links_to_local_pages_do_not_workDutiful
see #1475202Hyams
N
21

By definition, file: URLs are system-dependent, and they have little use. A URL as in your example works when used locally, i.e. the linking page itself is in the user’s computer. But browsers generally refuse to follow file: links on a page that it has fetched with the HTTP protocol, so that the page's own URL is an http: URL. When you click on such a link, nothing happens. The purpose is presumably security: to prevent a remote page from accessing files in the visitor’s computer. (I think this feature was first implemented in Mozilla, then copied to other browsers.)

So if you work with HTML documents in your computer, the file: URLs should work, though there are system-dependent issues in their syntax (how you write path names and file names in such a URL).

If you really need to work with an HTML document on your computers and another HTML document on a web server, the way to make links work is to use the local file as primary and, if needed, use client-side scripting to fetch the document from the server,

Naturalism answered 19/8, 2012 at 6:48 Comment(1)
Thank you for this.. I had been racking my head as to why my file links were not working. This needs to be marked as Answer!Bourbonism
T
13

Organize your files in hierarchical directories and then just use relative paths.

Demo:

HTML (index.html)

<a href='inner/file.html'>link</a>

Directory structure:

base/
base/index.html
base/inner/file.html
....
Thromboplastin answered 18/8, 2012 at 20:0 Comment(3)
I can't seem to do it this way, because the data folder and the scripts are in different locations. I tried doing ../../etc but it wouldn't go beyond the homepage of the site where the script is. It wouldn't go all the way up to C:/ +1 though for trying to help.Slurry
even you do not have the ideal directory structure, you can use base tag as shown inside my answer belowGerri
Is there any possibility within HTHML5 or CSS to inherit either content of the <a> tag or the destination from the respective counterpart? I'm linking to files and would like to ensure that the displayed link corresponds to the filename.Fredkin
G
6

The href value inside the base tag will become your reference point for all your relative paths and thus override your current directory path value otherwise - the '~' is the root of your site

    <head>
        <base href="~/" />
    </head>
Gerri answered 1/9, 2015 at 18:10 Comment(0)
T
2

This can happen when you are running IIS and you run the html page through it, then the Local file system will not be accessible.

To make your link work locally the run the calling html page directly from file browser not visual studio F5 or IIS simply click it to open from the file system, and make sure you are using the link like this:

<a href="file:///F:/VS_2015_WorkSpace/Projects/xyz/Intro.html">Intro</a>
Tadio answered 27/8, 2016 at 15:31 Comment(0)
F
1

The right way of setting a href=“” when it's a local file. It will not make any issue when code or file is online.

<a href="./your_file_name.html">FAQ</a>

Hope it will help you.

Finer answered 10/5, 2021 at 14:16 Comment(0)
C
0

../htmlfilename with .html User can do this This will solve your problem of redirection to anypage for local files.

Chelton answered 3/3, 2016 at 1:36 Comment(0)
G
0

Try swapping your colon : for a bar |. that should do it

<a href="file://C|/path/to/file/file.html">Link Anchor</a>
Glamour answered 13/12, 2019 at 19:44 Comment(1)
It might be helpful to the user if you explain why that should do it. I know I'd like to learn why that works.Choplogic
T
0

Here is the alternative way to download local file by client side and server side effort:

 <a onclick='fileClick(this)' href="file://C:/path/to/file/file.html"/>

Js: function fileClick(a) {

        var linkTag = a.href;
        var substring = "file:///";
        if (linkTag.includes(substring)) {
            var url = '/cnm/document/v/downloadLocalfile?path=' + encodeURIComponent(linkTag);
            fileOpen(url);
        }
        else {
            window.open(linkTag, '_blank');
        }
    }

    function fileOpen(url) {
        $.ajax({
            url: url,
            complete: function (jqxhr, txt_status) {
                console.log("Complete: [ " + txt_status + " ] " + jqxhr);
                if (txt_status == 'success') {
                    window.open(url, '_self');
                }
                else {
                    alert("File not found[404]!");
                }
                // }
            }
        });
    }

Server side[java]:

@GetMapping("/v/downloadLocalfile")
  public void downloadLocalfile(@RequestParam String path, HttpServletResponse 
        response) throws IOException, JRException {
      try {
          String nPath = path.replace("file:///", "").trim();
          File file = new File(nPath);
          String fileName = file.getName();
        
        response.setHeader("Content-Disposition", "attachment;filename=" +  
         fileName);
        if (file.exists()) {
            FileInputStream in = new FileInputStream(file);
            response.setStatus(200);
            OutputStream out = response.getOutputStream();
            byte[] buffer = new byte[1024];

            int numBytesRead;
            while ((numBytesRead = in.read(buffer)) > 0) {
                out.write(buffer, 0, numBytesRead);
            }
            // out.flush();
            in.close();
            out.close();
        }
        else {
            response.setStatus(404);
        }
      } catch (Exception ex) {
         logger.error(ex.getLocalizedMessage());
      }
    return;
}
Torrie answered 31/1, 2023 at 9:5 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.