Tomasz Waszczyk Tomasz Waszczyk - 13 days ago 6
AngularJS Question

Access to files on HDD from AngularJS application

I have AngularJS (1.2.16) application which works on Tomcat 8.0.x I need to add following feature: create a new tab in the application (no problem) and allows to user to select concrete from select box on previously implemented new tab, file from HDD (directory is given but outside from Tomcat) and preview (PDF file). How to connect those two worlds? I have backend also.

I have found very similar question- Simplest way to serve static data from outside the application server in a Java web application but I do not understand how to get in UI a list of files from given dir. There are any best practices on that?

EDIT: I have found also possible duplicate, so you suggest to serve all files under URL? Is it safe? Is it the only one solution?

Answer

Security considerations

Providing read/write access to a filesystem folder from an application server is always a bad practice.

It should be considered if the web application will be accessed from internet.

In case we need to handle this kind of situation the better think to do is to understand which information we need to have and to modify, and wen wrap those information inside a specific API that allow to work on strictly what we need.

Or we could have an operation approach which consists in the hardening of the server and the folders that should be accessed in a way that any threat will be contained.

The solution part

This answer was proposed for duplicate of: Simplest way to serve static data from outside the application server in a Java web application.

But this part just explain alf of the requested solution.

The answer here explain how to configure an extension of the default servlet from a custom folder in Tomcat:

You have to act on the conf/server.xml:

<Context docBase="/path/to/files" path="/files" />

Here you configure a folder in a way that Tomcat will access, and connect it to a path that could be requested on the HTTP requests (http://mytomcatserver/files/).

Now you need to configure the web.xml to connect a specific servlet to this path, to be able to handle the folder content.

Once you have your servlet and your Tomcat properly configured it's time to access the folder and files.

This could be done as explained int the answer Display list of files in webpage using servlet.

In short, you cold access the folder with plain java:

File filesFolder = new File(req.getSession().getServletContext().getRealPath("/files"));

And then with the method File.listFiles() you could get the list of files in the folder.

With File.listFiles() you could also add filters that allow you to hide files you don't want the user could access.

Comments