当前页面: 开发资料首页 → Netbeans 专题 → Using the File Upload Component
摘要: This tutorial describes how to use NetBeans Visual Web Pack 5.5 to upload and display an image (JPEG, PJPEG, GIF, PNG, or X-PNG) file. Also included is a mini-tutorial on how to upload a text file
JavaServer Faces Components/ Java EE Platform |
![]() ![]() | |||
Travel Database | ![]() |
|||
BluePrints AJAX Component Library | ![]() |
* As of the date this tutorial was published, only the Sun Java System Application Server supported Java EE 5.
This tutorial has been tailored for use with the Sun Java Application Server PE 9.0 Update Release 1 and with Tomcat 5.5.17. If you are using a different server, consult the Release Notes and FAQs for known problems and workarounds. For detailed information about the supported servers and Java EE platform, see the Release Notes.
The File Upload component enables users of your web application to locate a file on their system and upload that file to the server. This component is useful for collecting text files, image files, and other data. The contents of the uploaded file are stored together with some information about the file, including the file name, size, and MIME type (such as text/plain or image/jpeg).
The server holds the uploaded file in memory unless it exceeds 4096 bytes, in which case the server holds the file contents in a temporary file. You can change this threshold by modifying the sizeThreshold
parameter for the UploadFilter
filter entry in the web application's web.xml
file. For more information on modifying the web.xml
file, see the last section in this tutorial, Doing More: Modifying the Maximum File Upload Size.
In cases where you want to retain the uploaded file, you have three choices:
UploadedFile
property in a managed bean and set it to the component's value before you exit the page (as in the button's action method).
By default, the File Upload component can handle files up to one megabyte in size. You can change the maximum file size by modifying the maxSize
parameter for the UploadFilter
filter entry in the application's web.xml
file, as described in the last section in this tutorial, Doing More: Modifying the Maximum File Upload Size.
Create a new Visual Web Application project and name it FileUploadExample
.
Figure 1 shows the page that you will create in the steps that follow:
![]() Figure 1: File Upload Page Design |
Choose a File to Upload:
and press Enter.Upload File
, and press Enter. In the Properties window, set the Button's id
property to
uploadFileButton
.File Name:
id
property to fileNameStaticText
.File Type:
id
of the Static Text to fileTypeStaticText
. File Size:
and the id
of the Static Text to fileSizeStaticText
.Double-click the Upload File button to open the Java Editor and add the button's event handler, uploadFileButton_action, to the page bean.
Before adding code to this method, you define variables for storing the image file and add code to theinit()
and prerender()
methods.
Scroll up to the init()
method and add the following two variables before the method.
Code Sample 1: Variables |
private String realImageFilePath; private static final String IMAGE_URL = "/resources/image-file"; |
realImageFilePath
is the actual path and filename of the image file on the server. The IMAGE_URL
variable is the logical path of the image file in the running web application. Add the following lines of bold (shown in bold) at the end of the init
method, but note that the code contains a Class Not Found error. You add import statements to fix these errors in step 7. After inserting the code, you can press Ctrl-Shift-F to reformat the code.
Code Sample 2: init Method |
public void init() { super.init(); // Perform application initialization that must complete // *before* managed components are initialized // TODO - add your own initialiation code here // Managed Component Initialization // Perform application initialization that must complete // *after* managed components are initialized // TODO - add your own initialization code here ServletContext theApplicationsServletContext = (ServletContext) this.getExternalContext().getContext(); this.realImageFilePath = theApplicationsServletContext.getRealPath(IMAGE_URL); } |
IMAGE_URL
into the real image file path so that the file can be written to the correct directory on the server. Scroll to the prerender
method and add the following code:
Code Sample 3: prerender Method |
public void prerender() { String uploadedFileName = (String) this.fileNameStaticText.getValue(); if ( uploadedFileName != null ) { image1.setUrl(IMAGE_URL); } } |
Add the following code to the uploadFileButton_action()
method
Code Sample 4: Code to Upload an Image File |
public String uploadFileButton_action() { UploadedFile uploadedFile = fileUpload1.getUploadedFile(); String uploadedFileName = uploadedFile.getOriginalName(); // Some browsers return complete path name, some don't // Make sure we only have the file name // First, try forward slash int index = uploadedFileName.lastIndexOf('/'); String justFileName; if ( index >= 0) { justFileName = uploadedFileName.substring( index + 1 ); } else { // Try backslash index = uploadedFileName.lastIndexOf('\\'); if (index >= 0) { justFileName = uploadedFileName.substring( index + 1 ); } else { // No forward or back slashes justFileName = uploadedFileName; } } this.fileNameStaticText.setValue(justFileName); Long uploadedFileSize = new Long(uploadedFile.getSize()); this.fileSizeStaticText.setValue(uploadedFileSize); String uploadedFileType = uploadedFile.getContentType(); this.fileTypeStaticText.setValue(uploadedFileType); if ( uploadedFileType.equals("image/jpeg") || uploadedFileType.equals("image/pjpeg") || uploadedFileType.equals("image/gif") || uploadedFileType.equals("image/png") || uploadedFileType.equals("image/x-png")) { try { File file = new File(this.realImageFilePath); uploadedFile.write(file); } catch (Exception ex) { error("Cannot upload file: " + justFileName); } } else { error("You must upload a JPEG, PJPEG, GIF, PNG, or X-PNG file."); new File(this.realImageFilePath).delete(); } return null; } |
realImageFilePath
variable. If the file is not a valid image file or if there are other problems uploading the file, the program deletes the image from the server and displays an error message.
Right-click in the Java Editor and choose Fix Imports. In the Fix Import dialog box, ensure that java.io.File
appears in the Fully Qualified Name field and click OK.
Click Browse to navigate through your local drives and select a file to upload. Then click the Upload File button.
The following figure shows the application with an uploaded JPEG file. The image is stored in project-directory\FileUploadExample\build\web\resources
.
![]() Figure 2: Application With Uploaded Image |
Enter a text file in the File Upload component and click the Upload File button. Verify that the error message displays.
Note: The rendering of the File Upload component can differ depending on the web browser. Be sure to test this component in the web browsers that you expect your users to use.Double-click the Button component and add the following action code to the button1_action()
method:
Code Sample 5: Code to Upload a Text File |
public String button1_action() { UploadedFile uploadedFile = (UploadedFile) fileUpload1.getUploadedFile(); info("Uploaded file originally named '" + uploadedFile.getOriginalName() + "' of size '" + uploadedFile.getSize() + "'"); textArea1.setText(uploadedFile.getAsString()); return null; } |
UploadedFile
import statement. Run the application. The following figure shows a sample page.
![]() |
maxSize
parameter for the UploadFilter
filter in your application's web.xml
file. maxSize
parameter for the UploadFilter
, and click the Edit button.In the dialog box, set Param Value to the desired value and click OK.
Note: For security reasons, do not set themaxSize
parameter to a negative value, which indicates that there is no file size limit.
maxSize
parameter,
the following exception is thrown and caught as a validation error:org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededExceptionThe summary message displayed to users reads:
No file was uploadedThe detail message reads:
No file was uploaded. The specified file exceeds the maximum allowable size of 1000000 Mb
where 1000000 Mb is the value of maxSize
.
This tutorial shows how to upload a file to the web application's /resources
folder.
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:
Code Sample 6: Code to Upload a File to a Different Folder |
String realPath = theApplicationsServletContext.getRealPath("/upload/images"); File file = new File(realPath + File.separatorChar + justFileName); |
Be careful when putting the uploaded files in the web application because anyone can
access the files by URL, such as http://localhost:29080/MyWebApplication/faces/upload/images/myPicture.gif
.
A Known Directory on the Server
To store the images somewhere else on the server, you can use code such as the following:
Code Sample 7: Code to Upload a File to a Known Directory on a Server |
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 use code like the following to ensure that the upload directory exists:
Code Sample 8: Code to Upload a File to Different Servers |
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
Set the following values, and then click OK.
Param Name:uploadDirectory
(or whatever you want to name it)C:/upload/images
(or whatever your path is)web.xml
file.Use the following code:
Code Sample 9: Code to Upload a File to an As-Yet Unknown Directory |
String uploadDirectory = getExternalContext().getInitParameter ("uploadDirectory"); File file = new File(uploadDirectory + File.separatorChar + justFileName); uploadedFile.write(file); |
See Also: