📄 using.html
字号:
</li><li> Larger items should be written to a temporary file on disk. </li><li> Very large upload requests should not be permitted. </li><li> The built-in defaults for the maximum size of an item to be retained in memory, the maximum permitted size of an upload request, and the location of temporary files are acceptable. </li></ul></p><p> Handling a request in this scenario couldn't be much simpler: </p><div class="source"><pre>// Create a factory for disk-based file itemsFileItemFactory factory = new DiskFileItemFactory();// Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);// Parse the requestList /* FileItem */ items = upload.parseRequest(request);</pre></div><p> That's all that's needed. Really! </p><p> The result of the parse is a <code>List</code> of file items, each of which implements the <code>FileItem</code> interface. Processing these items is discussed below. </p></div><div class="section"><h3><a name="Exercising_more_control"></a>Exercising more control</h3><p> If your usage scenario is close to the simplest case, described above, but you need a little more control, you can easily customize the behavior of the upload handler or the file item factory or both. The following example shows several configuration options: </p><div class="source"><pre>// Create a factory for disk-based file itemsDiskFileItemFactory factory = new DiskFileItemFactory();// Set factory constraintsfactory.setSizeThreshold(yourMaxMemorySize);factory.setRepository(yourTempDirectory);// Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);// Set overall request size constraintupload.setSizeMax(yourMaxRequestSize);// Parse the requestList /* FileItem */ items = upload.parseRequest(request);</pre></div><p> Of course, each of the configuration methods is independent of the others, but if you want to configure the factory all at once, you can do that with an alternative constructor, like this: </p><div class="source"><pre>// Create a factory for disk-based file itemsDiskFileItemFactory factory = new DiskFileItemFactory( yourMaxMemorySize, yourTempDirectory);</pre></div><p> Should you need further control over the parsing of the request, such as storing the items elsewhere - for example, in a database - you will need to look into <a href="customizing.html">customizing</a> FileUpload. </p></div></div><div class="section"><h2><a name="Processing_the_uploaded_items"></a>Processing the uploaded items</h2><p> Once the parse has completed, you will have a <code>List</code> of file items that you need to process. In most cases, you will want to handle file uploads differently from regular form fields, so you might process the list like this: </p><div class="source"><pre>// Process the uploaded itemsIterator iter = items.iterator();while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) { processFormField(item); } else { processUploadedFile(item); }}</pre></div><p> For a regular form field, you will most likely be interested only in the name of the item, and its <code>String</code> value. As you might expect, accessing these is very simple. </p><div class="source"><pre>// Process a regular form fieldif (item.isFormField()) { String name = item.getFieldName(); String value = item.getString(); ...}</pre></div><p> For a file upload, there are several different things you might want to know before you process the content. Here is an example of some of the methods you might be interested in. </p><div class="source"><pre>// Process a file uploadif (!item.isFormField()) { String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory(); long sizeInBytes = item.getSize(); ...}</pre></div><p> With uploaded files, you generally will not want to access them via memory, unless they are small, or unless you have no other alternative. Rather, you will want to process the content as a stream, or write the entire file to its ultimate location. FileUpload provides simple means of accomplishing both of these. </p><div class="source"><pre>// Process a file uploadif (writeToFile) { File uploadedFile = new File(...); item.write(uploadedFile);} else { InputStream uploadedStream = item.getInputStream(); ... uploadedStream.close();}</pre></div><p> Note that, in the default implementation of FileUpload, <code>write()</code> will attempt to rename the file to the specified destination, if the data is already in a temporary file. Actually copying the data is only done if the the rename fails, for some reason, or if the data was in memory. </p><p> If you do need to access the uploaded data in memory, you need simply call the <code>get()</code> method to obtain the data as an array of bytes. </p><div class="source"><pre>// Process a file upload in memorybyte[] data = item.get();...</pre></div></div><div class="section"><h2><a name="Resource_cleanup"></a>Resource cleanup</h2><p> This section applies only, if you are using the <a href="apidocs/org/apache/commons/fileupload/disk/DiskFileItem.html">DiskFileItem</a>. In other words, it applies, if your uploaded files are written to temporary files before processing them. </p><p> Such temporary files are deleted automatically, if they are no longer used (more precisely, if the corresponding instance of <code>java.io.File</code> is garbage collected. This is done silently by the <code>org.apache.commons.io.FileCleaner</code> class, which starts a reaper thread. </p><p> This reaper thread should be stopped, if it is no longer needed. In a servlet environment, this is done by using a special servlet context listener, called <a href="apidocs/org/apache/commons/fileupload/servlet/FileCleanerCleanup.html">FileCleanerCleanup</a>. To do so, add a section like the following to your <code>web.xml</code>: </p><div class="source"><pre><web-app> ... <listener> <listener-class> org.apache.commons.fileupload.servlet.FileCleanerCleanup </listener-class> </listener> ...</web-app></pre></div><div class="section"><h3><a name="Creating_a_DiskFileItemFactory"></a>Creating a DiskFileItemFactory</h3><p> The FileCleanerCleanup provides an instance of <code>org.apache.commons.io.FileCleaningTracker</code>. This instance must be used when creating a <code>org.apache.commons.fileupload.disk.DiskFileItemFactory</code>. This should be done by calling a method like the following: </p><div class="source"><pre> public static DiskFileItemFactory newDiskFileItemFactory(ServletContext context, File repository) { FileCleaningTracker fileCleaningTracker = FileCleanerCleanup.getFileCleaningTracker(context); return new DiskFileItemFactory(fileCleaningTracker, DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, repository); }</pre></div></div><div class="section"><h3><a name="Disabling_cleanup_of_temporary_files"></a>Disabling cleanup of temporary files</h3><p> To disable tracking of temporary files, you may set the <code>FileCleaningTracker</code> to null. Consequently, created files will no longer be tracked. In particular, they will no longer be deleted automatically.</p></div></div><div class="section"><h2><a name="Interaction_with_virus_scanners"></a>Interaction with virus scanners</h2><p> Virus scanners running on the same system as the web container can cause some unexpected behaviours for applications using FileUpload. This section describes some of the behaviours that you might encounter, and provides some ideas for how to handle them. </p><p> The default implementation of FileUpload will cause uploaded items above a certain size threshold to be written to disk. As soon as such a file is closed, any virus scanner on the system will wake up and inspect it, and potentially quarantine the file - that is, move it to a special location where it will not cause problems. This, of course, will be a surprise to the application developer, since the uploaded file item will no longer be available for processing. On the other hand, uploaded items below that same threshold will be held in memory, and therefore will not be seen by virus scanners. This allows for the possibility of a virus being retained in some form (although if it is ever written to disk, the virus scanner would locate and inspect it). </p><p> One commonly used solution is to set aside one directory on the system into which all uploaded files will be placed, and to configure the virus scanner to ignore that directory. This ensures that files will not be ripped out from under the application, but then leaves responsibility for virus scanning up to the application developer. Scanning the uploaded files for viruses can then be performed by an external process, which might move clean or cleaned files to an "approved" location, or by integrating a virus scanner within the application itself. The details of configuring an external process or integrating virus scanning into an application are outside the scope of this document. </p></div><div class="section"><h2><a name="Watching_progress"></a>Watching progress</h2><p> If you expect really large file uploads, then it would be nice to report to your users, how much is already received. Even HTML pages allow to implement a progress bar by returning a multipart/replace response, or something like that. </p><p> Watching the upload progress may be done by supplying a progress listener: </p><div class="source"><pre>//Create a progress listenerProgressListener progressListener = new ProgressListener(){ public void update(long pBytesRead, long pContentLength, int pItems) { System.out.println("We are currently reading item " + pItems); if (pContentLength == -1) { System.out.println("So far, " + pBytesRead + " bytes have been read."); } else { System.out.println("So far, " + pBytesRead + " of " + pContentLength + " bytes have been read."); } }};upload.setProgressListener(progressListener);</pre></div><p> Do yourself a favour and implement your first progress listener just like the above, because it shows you a pitfall: The progress listener is called quite frequently. Depending on the servlet engine and other environment factory, it may be called for any network packet! In other words, your progress listener may become a performance problem! A typical solution might be, to reduce the progress listeners activity. For example, you might emit a message only, if the number of megabytes has changed: </p><div class="source"><pre>//Create a progress listenerProgressListener progressListener = new ProgressListener(){ private long megaBytes = -1; public void update(long pBytesRead, long pContentLength, int pItems) { long mBytes = pBytesRead / 1000000; if (megaBytes == mBytes) { return; } megaBytes = mBytes; System.out.println("We are currently reading item " + pItems); if (pContentLength == -1) { System.out.println("So far, " + pBytesRead + " bytes have been read."); } else { System.out.println("So far, " + pBytesRead + " of " + pContentLength + " bytes have been read."); } }};</pre></div></div><div class="section"><h2><a name="Whats_next"></a>What's next</h2><p> Hopefully this page has provided you with a good idea of how to use FileUpload in your own applications. For more detail on the methods introduced here, as well as other available methods, you should refer to the <a href="apidocs/index.html">JavaDocs</a>. </p><p> The usage described here should satisfy a large majority of file upload needs. However, should you have more complex requirements, FileUpload should still be able to help you, with it's flexible <a href="customizing.html">customization</a> capabilities. </p></div>
</div>
</div>
<div class="clear">
<hr/>
</div>
<div id="footer">
<div class="xright">©
2002-2008
The Apache Software Foundation
</div>
<div class="clear">
<hr/>
</div>
</div>
</body>
</html>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -