转载于:http://blog.csdn.net/hzc543806053/article/details/7524491
一、Servlet实现文件上传,需要添加第三方提供的jar包
下载地址:
1) commons-fileupload-1.2.2-bin.zip
接着把这两个jar包放到 lib文件夹下:
二:
文件上传的表单提交方式必须是POST方式,
编码类型:enctype="multipart/form-data",默认是 application/x-www-form-urlencoded
比如:<form action="FileUpLoad"enctype="multipart/form-data"method="post">
三、举例:
1.fileupload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<div id="cont">
<a href="../index.jsp">返回首页</a><br/><br/>
说明:<br/>
本demo描述简单上传文件功能;<br/>
简单上传文件可以利用上传文件后保存的FileInfo.noid的值获取到文件<br/>
<br/><br/><br/><br/>
<form action="upFile" method="post" enctype="multipart/form-data">
<table>
<tr><td>选择文件1:</td>
<td><input type="file" name="fldatas"/></td></tr>
<tr><td> </td>
<td><input type="submit" value="提交"/></td></tr>
</table>
</form>
<a href="getFileUrl.do?noid=${fi.noid}" target="_blank">${fi.srcFileName }</a>
</div>
</body>
</html>
2.实际处理文件上传的UpFileServlet.java
package com.cg;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UpFileServlet extends HttpServlet {
/**
*
* @author Administrator
* 文件上传
* 具体步骤:
* 1)获得磁盘文件条目工厂 DiskFileItemFactory 要导包
* 2) 利用 request 获取 真实路径 ,供临时文件存储,和 最终文件存储 ,这两个存储位置可不同,也可相同
* 3)对 DiskFileItemFactory 对象设置一些 属性
* 4)高水平的API文件上传处理 ServletFileUpload upload = new ServletFileUpload(factory);
* 目的是调用 parseRequest(request)方法 获得 FileItem 集合list ,
*
* 5)在 FileItem 对象中 获取信息, 遍历, 判断 表单提交过来的信息 是否是 普通文本信息 另做处理
* 6)
* 第一种. 用第三方 提供的 item.write( new File(path,filename) ); 直接写到磁盘上
* 第二种. 手动处理
*
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp)
throws ServletException, IOException {
try {
request.setCharacterEncoding("utf-8");
//获得磁盘文件条目工厂
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
//获取文件需要上传到的路径
String realPath = request.getSession().getServletContext().getRealPath("/upload");
//如果没以下两行设置的话,上传大的 文件 会占用 很多内存,
//设置暂时存放的 存储室 , 这个存储室,可以和 最终存储文件 的目录不同
/**
* 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上,
* 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的
* 然后再将其真正写到 对应目录的硬盘上
*/
diskFileItemFactory.setRepository(new File(realPath));
//设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室
diskFileItemFactory.setSizeThreshold(1024*1024);
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
List<FileItem> items = (List<FileItem>)servletFileUpload.parseRequest(request);
//可以上传多个文件
for(FileItem item:items){
String name = item.getFieldName();
if(item.isFormField()){
String value = item.getString();
request.setAttribute(name, value);
}else{
//获得文件的完整路径
String value = item.getName();
int start = value.lastIndexOf("\\");
//获得文件名
String fileName=value.substring(start+1);
request.setAttribute(name, fileName);
//调用第三方方法直接将文件写到磁盘
// item.write(new File(realPath, fileName));
//自己手动写入磁盘
OutputStream out = new FileOutputStream(new File(realPath,fileName));
InputStream in = item.getInputStream();
int leng = 0;
byte[] buf = new byte[1024];
while((leng = in.read(buf))!=-1){
out.write(buf,0,leng);
}
in.close();
out.close();
}
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
}