0

I'm building a web app in Python and Flask. This is the directory structure:

TopWebApp   
│
└───webApp
│   │   ui.py
│   │   back-end.py
│   │   result.txt
│   │
│   └───templates
│       │   index.html
│       │   ...
│   
└───venv
    | ...

In index.html, I have:

  <a href="C:\Users\...\webApp\result.txt" download>
    <button>click here</button>
  </a>

In chrome 70, when I click the "click here" button, nothing gets downloaded and if I open it in a new tab, the new tab will show "about::blank".

Since result.txt is saved under the same directory, I tried changing 'href=".result.txt"' and 'href="./result.txt"' but I get a Failed - No File when it downloads. Do you know why this happens?

Rking14
  • 325
  • 2
  • 5
  • 17

1 Answers1

1

The browser will prevent linking to local files (such as those on your C: drive) through hyperlinks, as a security measure. That includes hyperlinks with the download attribute. If you want to allow users to download from your server, you'll need to make the reference relative to your server itself. This can be done with an absolute like such as https://www.yourwebsite.com/yourfile.txt, though I would recommend using a relative link such as:

<a href="../result.txt" download>
  <button>click here</button>
</a>

Note that in this particular example, the file is one folder up from the file which is linking to it, so you need to traverse through your directory structure with ../.

If you are only opening up your file directly through File Explorer (as opposed to localhost, you'll need the file:/// prefix, as file:///C:/Users/.../webApp/result.txt. Note the three forward slashes at the start and the forward slash throughout.

Obsidian Age
  • 41,205
  • 10
  • 48
  • 71
  • I tried the above code. However, when the button is clicked, I get a "Failed - No file" download. Opening the link in new tab also generates a "404 Not Found". – Rking14 Nov 05 '18 at 22:48
  • So your `.txt` file is in the parent folder of your index file? Then `../result.txt` should work assuming you are running your website through something like `localhost` (or a proper server). If you are only opening up your file directly through File Explorer, you'll need the `file:///` prefix, as `file:///C:/Users/.../webApp/result.txt`. Note the three forward slashes at the start and the forward slash throughout. See [**this answer**](https://stackoverflow.com/a/18246357/2341603) for an explanation on why that is. – Obsidian Age Nov 05 '18 at 22:57
  • Yes, my .txt file is in the webApp folder which is the parent folder of the index.html file. I'm running the web app through localhost. Using 'file:///C:/Users/.../webApp/result.txt' works but it won't let me download the result.txt file and I'm unable to load in a new tab. – Rking14 Nov 05 '18 at 23:02