I want my servlet to receive files in some folder under the application directory tree. The server accepts files in multipart/form-data format. I've understood that @MultipartConfig
is the right attribute to mark the servlet code, to allow the server to create files. However, not every location is considered as safe, hence two questions:
- Which are the limitations, when specifying the locations for file-upload servlets
- Can the paths be relative to application path or they should be absolute?
- The files must be downloadable afterwards, so in general, which is a best place on the server to keep the files it (under the application tree, out of the tree, out of Tomcat tree etc?)
- Since annotation seems to be a very 'static' way to allow servlet download th开发者_StackOverflow中文版ings, can the same be specified in web.xml, for example?
Thanks!
1: Which are the limitations, when specifying the locations for file-upload servlets
It needs to be readable and writable. It also needs to be an existing location, the servletcontainer won't precreate it for you in case of absence.
2: Can the paths be relative to application path or they should be absolute?
Both are allowed, as long as 1) is confirmed. The container will under the covers use java.io.File
to denote the location. So using relative paths is definitely a bad idea.
3: The files must be downloadable afterwards, so in general, which is a best place on the server to keep the files it (under the application tree, out of the tree, out of Tomcat tree etc?)
Putting in webapp folder will cause them all get lost whenever you redeploy the webapp. It also won't work on some server configs since extraction of the WAR file is an optional configuration setting. So it's really better to put them on a fixed path outside the webapp folder. To download them again, just add a new <Context>
to Tomcat or create a servlet which gets a FileInputStream
from it and writes to OutputStream
of the response. Examples can be found in this answer.
4: Since annotation seems to be a very 'static' way to allow servlet download things, can the same be specified in web.xml, for example?
Yes, you can just ignore the location
attribute of the annotation altogether and use Part#getInputStream()
to write it to the desired location. You can then specify the location as <init-param>
of the servlet and initialize it in init()
method.
精彩评论