首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 服务器 > Apache >

Apache FileUpload的两种上传形式介绍

2013-04-02 
Apache FileUpload的两种上传方式介绍环境:tomcat5.6commmons-fileupload-1.3.jarcommmons-io-2.4.jar JSP

Apache FileUpload的两种上传方式介绍
环境:

tomcat5.6

commmons-fileupload-1.3.jar

commmons-io-2.4.jar

JSP

编码:UTF-8

临时文件夹:fileupload/tmp相对于网站根目录

上传文件保存位置:fileupload


Traditional API上传方式
//fileload01.htm
<%@page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" language="java"%><%@page import="java.io.*"%><%@page import="java.util.List"%><%@page import="org.apache.commons.fileupload.*"%><%@page import="org.apache.commons.fileupload.util.Streams"%><%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%><%request.setCharacterEncoding("UTF-8");// Check that we have a file upload requestif(ServletFileUpload.isMultipartContent(request)){// Create a new file upload handlerServletFileUpload upload = new ServletFileUpload();// Parse the requestFileItemIterator iter = upload.getItemIterator(request);while(iter.hasNext()){FileItemStream item = iter.next();String fieldName = item.getFieldName();InputStream is = item.openStream();if(item.isFormField())//regular form field{%><!-- read a FileItemStream's content into a string. --><h1><%=fieldName%> --> <%=Streams.asString(is)%></h1><%}else{//file uploadString fileName = item.getName();File uploadedFile = new File(getServletContext().getRealPath("/") +"fileupload" + File.separator + fieldName + "_" + fileName);OutputStream os = new FileOutputStream(uploadedFile);// write file to disk and close outputstream.Streams.copy(is, os, true);%><h1>upload file <%=uploadedFile.getName()%> done!</h1><%}}}%>


Traditional API vs Streaming API
Streaming API上传速度相对较快。因为它是利用内存保存上传的文件,节省了传统API将文件写入临时文件带来的开销。可参考:http://stackoverflow.com/questions/11620432/apache-commons-fileupload-streaming-apiThis 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 Streaming API.
http://commons.apache.org/proper/commons-fileupload/using.html






热点排行