使用common-fileupload框架实现文件上传

到http//jakarta.apache.org/commons/fileupload站点下载commons-fileupload-1.2.1-bin
到http//jakarta.apache.org/commons/io站点下载commons-io-1.4-bin
同时将两个文件解压开后,将commons-io-1.4.jar,commons-fileupload-1.2.1.jar文件拷贝到tomcat服务器Lib文件夹下面
index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

了解文件上传的原理

上传文件:
请求参数:

pro2.jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*, java.io.* "  %>
<%@ page import="java.util.*"%>
<%
	DiskFileItemFactory factory = new DiskFileItemFactory();
	factory.setSizeThreshold(1024*1024*20);
	factory.setRepository(new File(request.getRealPath("/")));
	ServletFileUpload upload = new ServletFileUpload(factory);
	upload.setSizeMax(1024*1024*20);
	List items = upload.parseRequest(request);
	for(Iterator it=items.iterator(); it.hasNext();){
		FileItem item = (FileItem)it.next();
		//判断是否为表单域
		if(item.isFormField()){
			String name = item.getFieldName();
			String value = item.getString("UTF-8");
			out.println("name=value:"+"name="+name+",value="+value);
		}else {
			//获取文件域名
			String fieldName = item.getFieldName();
			//获取文件名
			String fileName = item.getName();
			//获得文件类型
			String contentType = item.getContentType();
			FileOutputStream fos = new FileOutputStream(request.getRealPath("/") + System.currentTimeMillis()+
			fileName.subSequence(fileName.indexOf("."), fileName.length()));
			if(item.isInMemory()){
				fos.write(item.get());
			}else {
				InputStream is = item.getInputStream();
				byte [] buffer = new byte[1024];
				int len;
				while((len = is.read(buffer)) >1){
					fos.write(buffer, 0, len);
				}
				is.close();
				fos.close();
			}
			
		}
	}
	
%>





使用common-fileupdate框架上传文件





你可能感兴趣的:(使用common-fileupload框架实现文件上传)