设为首页 收藏本站
查看: 682|回复: 0

[经验分享] Apache Jakarta Project: commons FileUpload User Guide[翻译]

[复制链接]
发表于 2015-8-1 11:15:55 | 显示全部楼层 |阅读模式
  近一段时间都在为文件上传这件事焦心,总是找不合适的代码,自己水平差写不出什么好东西出来,所以问题一直拖到现在。今天在google上看到commons FileUpload的相关简介,马上就去Apache JakartaProject去找。哈哈……没错,就是它啦~
花了一个小时把它的E文Overview看了一下,觉得使用起来实在太方便了,短短地几句话就可以完成上传操作,真不赖,让我又可以小偷懒一把:P。下午,又写了一个简单的Bean来测试里面关键的类的使用,更具体的了解了它的方法作用的结果。再把那个E文User Guide主要的地方,在这里翻译一下。对于做页面上传文件的工作应该有一定的帮助。
  Using FileUpload
使用FileUpload
  FileUploadcan be used in a number of different ways, depending upon therequirements of your application. In the simplest case, you will call asingle method to parse the servlet request, and then process the listof items as they apply to your application. At the other end of thescale, you might decide to customize FileUpload to take full control ofthe way in which individual items are stored; for example, you mightdecide to stream the content into a database.
FileUpload可以根据应用程序的需求在很多不同的地方使用。举个很简单的例子,你可能调用一个简单的方法去编译servlet请求,并且把这些项目作为你的应用程序一部分来应用。从另一个方面来讲,你可能想自定义FileUpload来完成所有项目的存储;再来个例子,你可能想流化内容而存入数据库。
  Here, wewill describe the basic principles of FileUpload, and illustrate someof the simpler - and most common - usage patterns. Customization ofFileUpload is described elsewhere .
这里我们会介绍FileUpload基础的使用原则,并描述一些简单的通用的使用模式。关于FileUpload自定义的介绍会在其它地方(其实那里什么也没有)讲。
  How it works
简介
  Afile upload request comprises an ordered list of items that are encodedaccording to RFC 1867 , "Form-based File Upload in HTML". FileUploadcan parse such a request and provide your application with a list ofthe individual uploaded items. Each such item implements t he FileIteminterface, regardless of its underlying implementation.
一个上传请求由一系列根据RFC1867(这个文章我已经放在BLOG收藏夹HTML目录下)编码的项目。FileUpload可以编译这样的请求并将这一系列的个性化上传项目传递给你的应用程序。每一个这样的项目都实现了FielItem接口,不管它是怎么实现的。
  Eachfile item has a number of properties that might be of interest for yourapplication. For example, every item has a name and a content type, andcan provide an InputStream to access its data. On the other hand, youmay need to process items differently, depending upon whether the itemis a regular form field - that is, the data came from an ordinary textbox or similar HTML field - or an uploaded file. The FileItem interfaceprovides the methods to make such a determination, and to access thedata in the most appropriate manner.
每一个文件项目有一些自己的属性,这些属性也许正是你的应用程序感兴趣的地方。例如,每个项目有个一个名字和内容类型,并且可以提供一个输入流来访问这写数据。另一方面来看,你可能需要用不同方式来处理不同的项目,这就依赖与项目是否是一个正常的字域,也就是说,这些数据来自于一个普通的文本框或类似HTML的字域或一个上传文件。FileItem接口提供一些方法来做这样一个决定,并且访问这些数据用最合适的方法。
  FileUpload creates new file itemsusing a FileItemFactory . This is what gives FileUpload most of itsflexibility. The factory has ultimate control over how each item iscreated. The default factory stores the item's data in memory or ondisk, depending on the size of the item (i.e. bytes of data). However,this behavior can be customized to suit your application.
FileUpload使用FileItemFactory创建一个新的文件项目。对于FileUpload来说这是完全可行的。工厂是唯一全盘控制每个项目的创建的工具。默认的工厂存储项目的数据在内存或者硬盘里,这都依赖于项目的大小(如,数据字节数组)。不过,还是可以把它定义成为合适你的应用程序使用的。
  Parsing the request
  Beforeyou can work with the uploaded items, of course, you need to parse therequest itself. Ensuring that the request is actually a file uploadrequest is straightforward, but FileUpload makes it simplicity itself,by providing a static method to do just that.
在使用上传项目工作之前,你还需要编译请求。最重要的事情就要确定这个请求确实来自于文件上传,不过FileUpload利用一个静态方法使它自身简单化了。
  // Check that we have a file upload request
boolean isMultipart = FileUpload.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.
>>Thebuilt-in defaults for the maximum size of an item to be retained inmemory, the maximum permitted size of an upload request, and thelocation of temporary files are acceptable.
  下面是一些简单的使用场景:
>>上传项目只要足够小,就应该保留在内存里。
>>较大的项目应该被写在硬盘的临时文件上。
>>非常大的上传请求应该避免。
>>限制项目在内存中所占的空间,限制最大的上传请求,并且设定临时文件的位置。
  Handling a request in this scenario couldn't be much simpler:
处理这个场景的请求很简单:
  // Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload();
// Parse the request List
/* FileItem */ items = upload.parseRequest(request);
  That's all that's needed. Really!
这就是我们所需要的全部代码了!
  Theresult of the parse is a List of file items, each of which implementsthe FileItem interface. Processing these items is discussed below.
编译的结果就是生成了一系列文件项目,每个文件项目实现一个FileItem接口。下面将介绍如何处理这写项目。
  Exercising more control
控制练习
  Ifyour usage scenario is close to the simplest case, described above, butyou need a little more control over the size thresholds or the locationof temporary files, you can customize the behavior using the methods ofthe DiskFileUpload class, like this:
如果你的使用场景和最简单例子很接近,但是你又需要一点点扩展的控制,包括大小的极限或者临时文件的设置等,你可以通过DiskFileUpload类的方法来自定义行为,像这样:
  // Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload();
// Set upload parameters
upload.setSizeThreshold(yourMaxMemorySize);
upload.setSizeMax(yourMaxRequestSize);
upload.setRepositoryPath(yourTempDirectory);
// Parse the request List
/* FileItem */ items = upload.parseRequest(request);
  Ofcourse, each of the configuration methods is independent of the others,but if you want to configure them all at once, you can do that with analternate parseRequest() method, like this:
当然,每个配置方法是独立于其它任意一个的,但是如果你想一次性配置他们,你可以用parseRequest()的另一个重载方法,像这样:
  // Create a new file upload handler
DiskFileUpload upload = new DiskFileUpload();
// Parse the request List
/* FileItem */ items = upload.parseRequest(request, yourMaxMemorySize, yourMaxRequestSize, yourTempDirectory);
  Shouldyou need further control over the parsing of the request, such asstoring the items elsewhere - for example, in a database - you willneed to look into customizing FileUpload.
如果你还想使用更多的控制,比如存储项目到其它地方(如,数据库),那么你可以看FileUpload自定义(这个连接又是个假的,空页面)介绍。
  Processing the uploaded items
处理上传项目
  Oncethe parse has completed, you will have a List of file items that youneed to process. In most cases, you will want to handle file uploadsdifferently from regular form fields, so you might process the listlike 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);
   }
}
  Fora regular form field, you will most likely be interested only in thename of the item, and its String value. As you might expect, accessingthese is very simple.
对于普通的表单字域来说,你可能对项目的名称很感兴趣。完成你的需求真的很简单,照下面的做:
  // Process a regular form field
if (item.isFormField())
{
   String name = item.getFieldName();
   String value = item.getString(); ...
}
  Fora file upload, there are several different things you might want toknow before you process the content. Here is an example of some of themethods 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();
    ...
}
  Withuploaded 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 entirefile to its ultimate location. FileUpload provides simple means ofaccomplishing both of these.
对于上传的文件,你肯定不希望总是通过内存来访问它,除非它很小,或者你实在没有别的选择余地了。你很希望使用流来处理文件内容或者写文件实体到它最终的地址。FileUpload提供简单的方式,来完成两方面的需求。
  // Process a file upload
if (writeToFile)
{
    File uploadedFile = new File(...);
   item.write(uploadedFile);
}
else
{
   InputStream uploadedStream = item.getInputStream();
   ...
   uploadedStream.close();
}
  Notethat, in the default implementation of FileUpload, write() will attemptto rename the file to the specified destination, if the data is alreadyin a temporary file. Actually copying the data is only done if therename fails, for some reason, or if the data was in memory. If you doneed to access the uploaded data in memory, you need simply call theget() method to obtain the data as an array of bytes.
  注意:在FileUpload的默认实现中wirte()方法应该值得关注,如果数据还在临时文件没有移除,那么这个方法就会试图重命名这个文件为相应的目标文件。事实上如果重命名失败了的话,数据就仅仅被拷贝。如果你需要访问内存中的上传数据,你可以用get()方法来获得数据的二进制数组形式。
  // Process a file upload in memory
byte[] data = item.get(); ...
  What's next
下一步做什么
  Hopefullythis page has provided you with a good idea of how to use FileUpload inyour own applications. For more detail on the methods introduced here,as well as other available methods, you should refer to the JavaDocs .
希望这个文章对你使用FileUpload有一些帮助。对于更多的细节,还是要阅读配套的文档。
  Theusage described here should satisfy a large majority of file uploadneeds. However, should you have more complex requirements, FileUploadshould still be able to help you, with it's flexible customizationcapabilities.
这个使用简介应该是足够满足你大部分的需求。但是如果你有更复杂的需求的话,你还要自定义合适的可行方案。
  到这里就粗略的把用户指南翻译了一遍,刚刚开始学习使用这个工具包,理解难免有偏差,我还会随着具体的使用来完善一些细节方面的内容(没办法,官方网站没有这方面的介绍,只能自己摸索了,呵呵)。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-92959-1-1.html 上篇帖子: Apache HTTP最新官方配置(中译版) 下篇帖子: RESTful Java client with Apache HttpClient
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表