Saving Uploaded Files Uploaded by the File Upload Component

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 http://localhost:29080/MyWebApplication/faces/upload/images/myPicture.gif.

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.

  1. In the Files window, expand web and expand WEB-INF. Double-click web.xml to open it.

  2. 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)


  3. Close and save the web.xml file.

  4. Use the following code:
                    String uploadDirectory =
                            getExternalContext().getInitParameter("uploadDirectory");
                    File file = new File(uploadDirectory +
                            File.separatorChar +
                            justFileName);
                    uploadedFile.write(file);
    
Comments:

Post a Comment:
Comments are closed for this entry.
About

divas

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today