Saving Uploaded Files Uploaded by the File Upload Component
By divas on Jun 21, 2006
The Java Studio Creator File Upload tutorial shows how to upload a file to the web application's
/resources/images folder. But, what if you want to save the uploaded files elsewhere? Here are some alternatives.
A different folder in the web application.You can put the images in any directory in the web application (that is, any directory under the web application's
web directory). For example, you can create an
upload/images subfolder under
web and use the following code to store the images there:
String realPath = theApplicationsServletContext.getRealPath ("/upload/images"); File file = new File(realPath + File.separatorChar + justFileName);
One thing you need to be careful about when putting the uploaded files in the web application, is that anyone can access the files by URL, such as
A known directory on the server. If you want to store the images somewhere else on the server, you can use code like the following:
File file = new File("C:/upload/images" + File.separatorChar + justFileName); uploadedFile.write(file);
If you plan to deploy the application to different servers, you might want to use code like the following to ensure that the upload directory exists:
File dir = new File("C:/upload/images"); if (! dir.exists()) dir.mkdirs(); File file = new File(dir.getCanonicalPath() + File.separatorChar + justFileName); uploadedFile.write(file);
For more information about the File class, see http://java.sun.com/j2se/1.3/docs/api/java/io/File.html.
An as yet unknown directory. An alternative is to put the directory path in the deployment descriptor, so that you can change the location dynamically.
- In the Files window, expand web and expand WEB-INF. Double-click web.xml to open it.
- Click the Context Parameter Add button, set the following values, and click OK.
Param Name: uploadDirectory (or whatever you want to name it)
Param Value: C:/upload/images (or whatever your path is)
- Close and save the web.xml file.
- Use the following code:
String uploadDirectory = getExternalContext().getInitParameter("uploadDirectory"); File file = new File(uploadDirectory + File.separatorChar + justFileName); uploadedFile.write(file);