简体   繁体   中英

How to view local files in web browser by displaying and creating a link to local files stored in your computer in your webApp?

I have created a webapp using JSP,Html and Javascript which currently runs on my localhost using apache webserver. I want to display the files and folders and of a directory in local computer. I also want to create a download link or view link of those so that when anyone click on it it will be viewed in new tab or become downloadable as it happens in any ftp server. I know similar type of question has been asked but none of them worked for me. To create the download link I used

<a href="D:/mylocaldrive/a.png" download="a.png">Download</a>

this does not work as it is not in my webapp path and download attribute also does not work in internet explorer.

I'm not sure why you are exposing your local drive contents on the web but here's an option:

  1. On the page that should display the files, in java code, list all folders and files then for each file/folder show a link to some page (for example "navigateLocalDrive" that sends the path of the clicked file/folder like this:

<a href="/navigateLocalDrive.jsp?file=D%3A%2Fmylocaldrive%2Fa.png">Download</a>

  1. Now in that jsp, check if the GET variable is a path for a file or a directory, if its a file, just send it back in the response, if its a directory, list all files/folders and do the same as in step 1

Please note:

  • How I encoded the file path in the href in order to work properly.
  • The Access permissions for the webserver should allow write/read to that path (I'm already doing it on my Tomcat server on local host with the default setup no change needed)

For your reference, here are some helpers for this task:

I am not sure if this is possible. In general the access rights are limited to the src and webContent Folder (for your html coding mentioned above for sure) . This is also reasonable, because you do not want to access or change data on your Computer in general, because after local development you want to deploy your web application to a server.

To make a test copy some file to the webContent and you will be able to download it. Within your Java coding you can use some IO package like java.io.File to navigate over folders and files. However keep in mind, that you will get some exceptions like

java.io.FileNotFoundException: C:\WeatherExports\export.txt (Access is denied)

if you want to access files outside the server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM