好久没有搞过上传的东西了,最近要对一个系统进行“改装”一下,原来用到的好多东西都要更换一下,并增加一些新功能,用到了fileupload,于是就重新学习了一下。一下是从apache官网粘帖过来的,写的不错。绝对够用了。
Parsing the request
Before you can work with the uploaded items, of course, you need to parse the request itself. Ensuring that the request is actually a file upload request is straightforward, but FileUpload makes it simplicity itself, by providing a static method to do just that.
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
Now we are ready to parse the request into its constituent items.
The simplest case
The simplest usage scenario is the following:
- Uploaded items should be retained in memory as long as they are reasonably small.
- Larger items should be written to a temporary file on disk.
- Very large upload requests should not be permitted.
- 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.
Handling a request in this scenario couldn't be much simpler:
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
That's all that's needed. Really!
The result of the parse is a List
of file items, each of which implements the FileItem
interface. Processing these items is discussed below.
Exercising more control
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:
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(yourMaxMemorySize);
factory.setRepository(yourTempDirectory);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(yourMaxRequestSize);
// Parse the request
List /* FileItem */ items = upload.parseRequest(request);
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:
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory(
yourMaxMemorySize, yourTempDirectory);
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 customizing FileUpload.
Processing the uploaded items
Once the parse has completed, you will have a List
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:
// Process the uploaded items
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
processFormField(item);
} else {
processUploadedFile(item);
}
}
For a regular form field, you will most likely be interested only in the name of the item, and its String
value. As you might expect, accessing these is very simple.
// Process a regular form field
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString();
...
}
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.
// Process a file upload
if (!item.isFormField()) {
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
...
}
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.
// Process a file upload
if (writeToFile) {
File uploadedFile = new File(...);
item.write(uploadedFile);
} else {
InputStream uploadedStream = item.getInputStream();
...
uploadedStream.close();
}
Note that, in the default implementation of FileUpload, write()
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.
If you do need to access the uploaded data in memory, you need simply call the get()
method to obtain the data as an array of bytes.
// Process a file upload in memory
byte[] data = item.get();
...
Resource cleanup
This section applies only, if you are using the DiskFileItem . In other words, it applies, if your uploaded files are written to temporary files before processing them.
Such temporary files are deleted automatically, if they are no longer used (more precisely, if the corresponding instance of java.io.File
is garbage collected. This is done silently by theorg.apache.commons.io.FileCleaner
class, which starts a reaper thread.
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 FileCleanerCleanup . To do so, add a section like the following to your web.xml
:
<web-app>
...
<listener>
<listener-class>
org.apache.commons.fileupload.servlet.FileCleanerCleanup
</listener-class>
</listener>
...
</web-app>
Creating a DiskFileItemFactory
The FileCleanerCleanup provides an instance of org.apache.commons.io.FileCleaningTracker
. This instance must be used when creating aorg.apache.commons.fileupload.disk.DiskFileItemFactory
. This should be done by calling a method like the following:
public static DiskFileItemFactory newDiskFileItemFactory(ServletContext context,
File repository) {
FileCleaningTracker fileCleaningTracker
= FileCleanerCleanup.getFileCleaningTracker(context);
return new DiskFileItemFactory(fileCleaningTracker,
DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD,
repository);
}
Disabling cleanup of temporary files
To disable tracking of temporary files, you may set the FileCleaningTracker
to null. Consequently, created files will no longer be tracked. In particular, they will no longer be deleted automatically.
Interaction with virus scanners
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.
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).
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.
Watching progress
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.
Watching the upload progress may be done by supplying a progress listener:
//Create a progress listener
ProgressListener 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);
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:
//Create a progress listener
ProgressListener 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.");
}
}
};
在此记录一下,最近比较郁闷,不知道为什么有时候就登陆不了javaeye,还有javaeye的编辑器,我怎么都不会用,还有那个附件上传的,word都不让传。。闹心。希望改进一下,不然我就要搬家了。O(∩_∩)O哈!
分享到:
相关推荐
这个"fileupload使用方法demo"是基于Apache Commons FileUpload 1.2.1版本的一个示例,帮助开发者了解如何在实际项目中集成并使用该库。 首先,我们来理解一下Apache Commons FileUpload的基本工作原理。在HTTP协议...
本篇文章将详细介绍如何使用Apache Commons FileUpload来实现文件上传操作。 首先,我们需要了解HTTP协议在处理文件上传时的机制。通常,文件上传是通过`multipart/form-data`编码类型实现的,这种编码方式允许在...
### FileUpload 使用文档详解 #### 一、概述 在当今互联网时代,文件上传已经成为网站交互不可或缺的一部分。无论是发送电子邮件附件还是分享个人照片,文件上传功能都扮演着重要角色。然而,实现这一功能并非易事...
使用FileUpload组件实现上传功能,供大家一起共同分享学习。
在IT行业中,文件上传是许多应用程序的基本功能,无论是网页、移动应用还是桌面软件,都可能涉及到用户上传文件的...通过以上信息,开发者可以轻松集成和使用Apache FileUpload组件,实现高效且可靠的文件上传功能。
本文将深入讲解如何使用FileUpload进行文件上传操作,并提供相关的开发参考。 1. **FileUpload库介绍** Apache Commons FileUpload库为Servlet环境提供了处理multipart/form-data请求的能力,这是HTML表单上传文件...
2. **分割多部分数据**:FileUpload使用`DiskFileItemFactory`来创建`FileItem`对象,每个`FileItem`代表请求中的一部分数据,可以是文本字段或上传的文件。 3. **内存与磁盘管理**:`DiskFileItemFactory`提供了一...
.NET 文件上传文件控件(FileUpload)使用实例 .NET Framework 提供了一个名为 FileUpload 的控件,用于实现文件上传功能。本文将通过一个简单的图片上传程序,来演示 FileUpload 控件的使用实例。 在 ASP.NET 中...
在commons-fileupload1.4更高版本更新前可以暂时适应Javax改为jakarta,目前jar包修改了引用类,将原有Servlet*改为JakSrvlt*即可使用,例如 ServletFileUpload改为JakSrvltFileUpload,即可在JavaEE8+以及Tomcat10...
SpringMVC上传文件FileUpload使用方法详解 在本文中,我们将详细介绍 SpringMVC 上传文件 FileUpload 的使用方法,旨在帮助开发者快速掌握该技术。下面是相关知识点的总结: 一、SpringMVC 上传文件 FileUpload ...
在配合Commons FileUpload使用时,它可以协助处理上传文件的临时存储和最终保存。 在实现文件上传功能时,通常会遵循以下步骤: 1. **前端HTML表单设计**:创建一个包含`enctype="multipart/form-data"`属性的表单...
- **实现类**:FileUpload使用`DiskFileItem`和`MemoryFileItem`两个实现类来存储上传的文件数据。这些实现类负责管理文件数据的存储位置(内存或磁盘)。 #### 三、使用方式 FileUpload提供了两种主要的API来处理...
通过以上步骤,我们就使用Apache Commons FileUpload组件实现了一个基本的文件上传功能。你可以根据自己的需求对这个示例进行扩展,比如添加错误处理、文件类型检查和存储优化等。参考提供的博文链接,可以获取更多...
使用fileupload组件实现文件上传功能 FileUpload组件是Apache提供的一款文件上传组件,能够帮助我们轻松实现文件上传功能。下面我们将详细介绍使用FileUpload组件实现文件上传功能的步骤和要点: 首先,需要引入两...
"FileUpload 控件的使用" FileUpload 控件是 ASP.NET 中一个常用的控件,用于上传文件到服务器端。在 Web 开发中,文件上传是一个非常常见的需求,例如上传头像、上传附件等。FileUpload 控件提供了一个简单的方式...
### FileUpload组件使用方法详解 #### 一、简介 FileUpload组件是Apache Commons项目下的一个子项目,专门用于处理HTTP POST请求中的文件上传问题。它能够解析来自客户端的多部分请求数据流,并将它们转换为一种...
FileUpload控件的使用方法 FileUpload控件是ASP.NET中的一个控件,用于实现文件上传功能。下面是使用FileUpload控件上传文件的详细步骤: 1. 首先,需要在ASP.NET web表单中添加一个FileUpload控件。可以在Visual ...
开发工具 commons-fileupload-1.3.2开发工具 commons-fileupload-1.3.2开发工具 commons-fileupload-1.3.2开发工具 commons-fileupload-1.3.2开发工具 commons-fileupload-1.3.2开发工具 commons-fileupload-1.3.2...
ASP.NET的FileUpload控件是Web开发中用于处理文件上传功能的重要组件。它允许用户从他们的本地计算机选择一个或多个文件,并将这些文件上传到服务器。在本文中,我们将深入探讨FileUpload控件的基本用法,包括如何在...
- 可以使用`FileUpload.PostedFile.ContentType`检查文件类型,使用`FileUpload.PostedFile.ContentLength`检查文件大小。 - 应该在服务器端验证所有文件,即使客户端已经进行了验证。 6. **文件保存** - 文件...