I am building application using JSP and servlet. I am trying to build a file uploading functionality in it. I want to make sure that the folder structure that I create locally gets transferred to the Apache web server. What are the ways to achieve this? I have a form where I give the path to a specific folder using input file control. When I submit the form whatever hierarchy of files and folders under the selected folder in form should get created on the web server. If the folder contains any files then the file/s should automatically get transferred to the server. Is it possible to make such kind of functionality?
1 Answers
When a file is uploaded, you normally get only the file name and the file content. You normally don't get the whole client side disk file system path as well. Only the poor MSIE webbrowser will due to a security bug incorrectly send this information along, but you should trim this off on /
or \
and end up with only the file name, or if you're using Apache Commons FileUpload, by FilenameUtils#getName()
.
As to the server side folder structure, just store the uploaded file under an unique name in a fixed folder. Don't unnecessarily create additional folders, unless the folder is supposed to identify the logged-in user or something, of course. You can use File#createTempFile()
to create unique file names based on a filename prefix and filename suffix (extension) to avoid uploaded files with by coincidence the same name being overwritten.
As to the server side upload folder location, make sure that it's not in the webapp's deploy folder in the server's folder structure. This would namely get lost everytime whenever you redeploy the webapp, with the simple reason that the newly added/changed files after upload are not contained in the to-be-deployed WAR.
As to serving the files, just add the upload folder location as another virtual host to the server config. It's unclear what exactly you mean with "Apache web server" as Apache is an enormous software company building many, many software prodcuts. Do you mean Apache HTTPD? Apache Tomcat? Apache TomEE? Apache Geronimo? Etc.. As you're talking in JSP/Servlet context, I'll assume Apache Tomcat. Head then to this answer: How I save and retrieve an image on my server in a java webapp.