9 JSP 文件上传下载.doc

上传人:啊飒飒 文档编号:10838758 上传时间:2021-06-07 格式:DOC 页数:14 大小:162.50KB
返回 下载 相关 举报
9 JSP 文件上传下载.doc_第1页
第1页 / 共14页
9 JSP 文件上传下载.doc_第2页
第2页 / 共14页
9 JSP 文件上传下载.doc_第3页
第3页 / 共14页
9 JSP 文件上传下载.doc_第4页
第4页 / 共14页
9 JSP 文件上传下载.doc_第5页
第5页 / 共14页
点击查看更多>>
资源描述

《9 JSP 文件上传下载.doc》由会员分享,可在线阅读,更多相关《9 JSP 文件上传下载.doc(14页珍藏版)》请在三一文库上搜索。

1、MyEclipse 6 实战开发讲解视频入门 10 JSP 文件上传下载2007-12-2本视频讲解了如何使用最新版本开源的Apache Commons FileUpload 来上传文件以及如何编写文件下载代码. 视频部分代码屏幕出现闪烁, 错位, 不便之处请参考本文中的源码和文档中绿色部分的注释:/ Set factory constraintsfactory.setSizeThreshold(yourMaxMemorySize); / 设置最多只允许在内存中存储的数据,单位:字节factory.setRepository(yourTempDirectory); / 设置一旦文件大小超过ge

2、tSizeThreshold()的值时数据存放在硬盘的目录(默认可以不用设置)/ Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);/ Set overall request size constraint/ 设置允许用户上传文件大小,单位:字节upload.setSizeMax(yourMaxRequestSize);友情提示: 下载微软网盘文件时关闭下载工具, 否则你将得到错误的文件, 双击 EXE 会出来 DOS 窗口. 正确操作是点击文件名后能看到显示下载链

3、接和文件大小等信息. 代码: http:/cid- 132 KB 视频: http:/cid- 16分31秒 6.0 MB 内容包括: 1. Apache Commons FileUpload 项目介绍 2. 下载并增加必要的类库 3. 编写文件上传表单 HTML 4. 编写文件上传处理 JSP 5. 编写文件下载JSP 6. 发布并测试 视频截图: 代码: upload.htm Login: Password: 附件: upload.jsp 0) fileName = fileName.substring(fileName.lastIndexOf(/) + 1, fileName.lengt

4、h(); return fileName; return ; %相关资料: 下载地址 http:/commons.apache.org/fileupload/ http:/commons.apache.org/io/ 用法文档: http:/commons.apache.org/fileupload/using.html Using FileUploadFileUpload can be used in a number of different ways, depending upon the requirements of your application. In the simplest

5、 case, you will call a single method to parse the servlet request, and then process the list of items as they apply to your application. At the other end of the scale, you might decide to customize FileUpload to take full control of the way in which individual items are stored; for example, you migh

6、t decide to stream the content into a database. Here, we will describe the basic principles of FileUpload, and illustrate some of the simpler - and most common - usage patterns. Customization of FileUpload is described elsewhere. FileUpload depends on Commons IO, so make sure you have the version me

7、ntioned on the dependencies page in your classpath before continuing. How it worksA file upload request comprises an ordered list of items that are encoded according to RFC 1867, Form-based File Upload in HTML. FileUpload can parse such a request and provide your application with a list of the indiv

8、idual uploaded items. Each such item implements the FileItem interface, regardless of its underlying implementation. This page describes the traditional API of the commons fileupload library. The traditional API is a convenient approach. However, for ultimate performance, you might prefer the faster

9、 Streaming API. Each file item has a number of properties that might be of interest for your application. For example, every item has a name and a content type, and can provide an InputStream to access its data. On the other hand, you may need to process items differently, depending upon whether the

10、 item is a regular form field - that is, the data came from an ordinary text box or similar HTML field - or an uploaded file. The FileItem interface provides the methods to make such a determination, and to access the data in the most appropriate manner. FileUpload creates new file items using a Fil

11、eItemFactory. This is what gives FileUpload most of its flexibility. The factory has ultimate control over how each item is created. The factory implementation that currently ships with FileUpload stores the items data in memory or on disk, depending on the size of the item (i.e. bytes of data). How

12、ever, this behavior can be customized to suit your application. Servlets and PortletsStarting with version 1.1, FileUpload supports file upload requests in both servlet and portlet environments. The usage is almost identical in the two environments, so the remainder of this document refers only to t

13、he servlet environment. If you are building a portlet application, the following are the two distinctions you should make as you read this document: Where you see references to the ServletFileUpload class, substitute the PortletFileUpload class. Where you see references to the HttpServletRequest cla

14、ss, substitute the ActionRequest class. Parsing the requestBefore 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 me

15、thod to do just that. / Check that we have a file upload requestboolean isMultipart = ServletFileUpload.isMultipartContent(request);Now we are ready to parse the request into its constituent items. The simplest caseThe simplest usage scenario is the following: Uploaded items should be retained in me

16、mory 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

17、 of temporary files are acceptable. Handling a request in this scenario couldnt be much simpler: / Create a factory for disk-based file itemsFileItemFactory factory = new DiskFileItemFactory();/ Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);/ Parse the req

18、uestList /* FileItem */ items = upload.parseRequest(request);Thats all thats 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 controlIf your usage scenario is close to the simp

19、lest 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 itemsDiskFileItemFactory factory = new DiskF

20、ileItemFactory();/ Set factory constraintsfactory.setSizeThreshold(yourMaxMemorySize); / 设置最多只允许在内存中存储的数据,单位:字节factory.setRepository(yourTempDirectory); / 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录(默认可以不用设置)/ Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);/

21、Set overall request size constraint/ 设置允许用户上传文件大小,单位:字节upload.setSizeMax(yourMaxRequestSize);/ Parse the requestList /* 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, y

22、ou can do that with an alternative constructor, like this: / Create a factory for disk-based file itemsDiskFileItemFactory factory = new DiskFileItemFactory( yourMaxMemorySize, yourTempDirectory);Should you need further control over the parsing of the request, such as storing the items elsewhere - f

23、or example, in a database - you will need to look into customizing FileUpload. Processing the uploaded itemsOnce 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 migh

24、t process the list like this: / Process the uploaded itemsIterator 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

25、 the name of the item, and its String value. As you might expect, accessing these is very simple. / Process a regular form fieldif (item.isFormField() String name = item.getFieldName(); String value = item.getString(); .For a file upload, there are several different things you might want to know bef

26、ore you process the content. Here is an example of some of the methods you might be interested in. / Process a file uploadif (!item.isFormField() String fieldName = item.getFieldName(); String fileName = item.getName(); String contentType = item.getContentType(); boolean isInMemory = item.isInMemory

27、(); 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

28、provides simple means of accomplishing both of these. / Process a file uploadif (writeToFile) File uploadedFile = new File(.); item.write(uploadedFile); else InputStream uploadedStream = item.getInputStream(); . uploadedStream.close();Note that, in the default implementation of FileUpload, write() w

29、ill 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()

30、 method to obtain the data as an array of bytes. / Process a file upload in memorybyte data = item.get();.Resource cleanupThis 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 tempo

31、rary 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 an instance of mons.io.FileCleaningTracker, which starts a reaper thread. In what follows, we assume that you are writing a w

32、eb application. In a web application, resource cleanup is controlled by an instance of javax.servlet.ServletContextListener. In other environments, similar ideas must be applied. The FileCleanerCleanupYour web application should use an instance of mons.fileupload.FileCleanerCleanup. Thats very easy,

33、 youve simply got to add it to your web.xml: . mons.fileupload.servlet.FileCleanerCleanup .Creating a DiskFileItemFactoryThe FileCleanerCleanup provides an instance of mons.io.FileCleaningTracker. This instance must be used when creating a mons.fileupload.disk.DiskFileItemFactory. This should be don

34、e 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 filesTo disable tracking of temporary files, you may set the FileCleaningTracker to null. Consequently, created files will no longer be tracked. In particul

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 科普知识


经营许可证编号:宁ICP备18001539号-1