1

I have a Java webapp running on Tomcat. At runtime, I create images files that I want to be publicly published on the tomcat server.

1/ How can I get the local URL where I want to copy my image files? (ie /mylocalpath/to/where/i/should/store/the/file/)

2/ How can I know the URL where other machines can access this public files? (ie http://mydomainname/myapp/myresource.png)

Mick F
  • 7,312
  • 6
  • 51
  • 98
  • possible duplicate of [Accessing Tomcat directory path](http://stackoverflow.com/questions/4546901/accessing-tomcat-directory-path), [reliable data serving](http://stackoverflow.com/questions/1502841/reliable-data-serving), [load image outside webcontext](http://stackoverflow.com/questions/4543936/load-the-image-from-outside-of-webcontext-in-jsf) and possibly many more. – BalusC Nov 05 '11 at 22:56

2 Answers2

1

Keep the path in a servlet init-param, a JNDI string, or in a property file. (Or whatever is provided by your framework that allows simple configuration.)

Create a servlet/action/controller/etc. that's mapped to a known URL. Either pass in a param with the filename or make the filename part of the URL. Stream the contents of the file back to the user. (Search for "image servlet" for examples.)

Bear in mind the mime type of the file and set the appropriate header. If necessary, check if the requesting user has access to the file in question. (There are several ways to implement that.)

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
  • Thanks. I get to know a little better what a solution could be. But the thing is i don't want to stream the file back to the user directly. I want to give the URL only. And then, the other party can request this URL whenever it wants. I guess a solution could be that a dedicated servlet keeps a Map of all the generated items, identified by an arbitrary key, and associated to the local path of the file. Thus, i can send an URL like http://toto.com/myapp/image?id=xxx and do the trick. What do you think? – Mick F Nov 02 '11 at 02:34
  • 1
    There *is* a URL, the streaming servlet. You can't give a URL that's not in the app context. – Dave Newton Nov 02 '11 at 02:40
0

I've figured a much simpler way to do this (which may sound obvious to Tomcat experts but useful to others).

In Tomcat 6 "server.xml" file, I've added this line in the <Host> element :

<Context docBase="/mylocalpath/to/where/i/should/store/the/file" path="/uploads" />

Then, when i create my resource i copy it in this local directory and figure out the public URL pretty easily : http://myserver/uploads/myfilename

Hope it can help other people.

(I even think the context can be defined in a context.xml included in the WAR rather than in Tomcat's global configuration but a global definition was enough for my needs).

Mick F
  • 7,312
  • 6
  • 51
  • 98