0

I am running a Java J2EE app in Tomcat and I would like to upload some files that can be directly served by Tomcat via URL (ie, I don't want to create an additional servlet to serve the files and I don't want to use Apache).

What is the solution to this? I know I should not create files inside the deployed WAR directory (if it is extracted at all), as illustrated in this very old post.

I tried creating another directory under "webapps":

System.getProperty("catalina.base") + "/webapps/uploadedFiles/";

but Tomcat does not seem to serve any file at "localhost:8080/uploadedFiles/...". So I had to put the files inside the webapps/ROOT directory, were they could be accessed. However, this looks ugly and it's probably not really correct, because I think the ROOT directory is not designed for such purposes.

My question is:

HOW CAN I MAKE TOMCAT SERVE my upload files, considering that they cannot be placed in the deployed directory because they can be overwritten?

Or, what is the same: where should I place my upload files so Tomcat can serve them directly via HTTP request and they don't get overwritten by redeployment?

user1156544
  • 1,725
  • 2
  • 25
  • 51
  • 1
    I personally like to define a place for them completely outside tomcat and configure Apache to send requests directly to this directory, but because your answer doesn't mention Apache or deployment specific configurations i write this as a comment. But this would be one way to do it. – ug_ Jun 29 '14 at 07:09
  • Thanks. As you mention, I am not using Apache, only Tomcat – user1156544 Jun 29 '14 at 21:32
  • This is not opinion-based at all ... – Stefan Jun 30 '14 at 08:21
  • I am sorry but I am not asking for opinion (e.g. if you like to place upload files inside a deployed WAR or in a directory called "my_files"), I am asking HOW can I make Tomcat to serve directly the files I upload (which cannot be in the WAR directory because they can get overwritten). – user1156544 Jun 30 '14 at 14:17

1 Answers1

2

Saving uploaded file (don't use getRealPath() nor part.write()!)

Head to the following answers for detail on properly saving the obtained InputStream (the fileContent variable as shown in the above code snippets) to disk or database:

Serving uploaded file

Head to the following answers for detail on properly serving the saved file from disk or database back to the client:

Source

Community
  • 1
  • 1
user1156544
  • 1,725
  • 2
  • 25
  • 51