文件上传页面
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>using commons Upload to upload file</title>
</head>
<style>
* {
font-family: "宋体";
font-size: 14px
}
</style>
<body>
<p align="center">
请您选择需要上传的文件
</p>
<form id="form1" name="form1" method="post"
action="<%=request.getContextPath()%>/servlet/uploadFile"
enctype="multipart/form-data">
<table border="0" align="center">
<tr>
<td>
上传人:
</td>
<td>
<input name="name" type="text" id="name" size="20">
</td>
</tr>
<tr>
<td>
上传文件:
</td>
<td>
<input name="file1" type="file" size="20">
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" name="Submit" value="提交">
<input type="reset" name="Reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
servlet
package com.v512.upload;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
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 UploadServlet extends HttpServlet {
/**
* 文件上传的servlet
*/
private static final long serialVersionUID = 1L;
private String savePath;
ServletContext sc;
public void init(ServletConfig config) {
savePath = config.getInitParameter("savePath");
sc = config.getServletContext();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = (List) upload.parseRequest(request);//解析表单传递过来的信息
Iterator it = items.iterator();//迭代这些信息
while (it.hasNext()) {
FileItem item = (FileItem) it.next();
if (item.isFormField()) {
System.out.println("表单参数名:" + item.getFieldName()
+ ",表单参数值:" + item.getString("UTF-8"));
} else {
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
//下面这行代码是获取上传文件在客户端完整的路径
System.out.println("上传文件的名称:" + item.getName());
File tempFile = new File(item.getName());
// sc.getRealPat("/")获取项目(根目录)在web服务器中的路径
File file = new File(sc.getRealPath("/") + savePath,
tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request,
response);
}
}
返回页面
<%@ page language="java" contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>upload result page</title>
</head>
<style>
* { font-family: "宋体"; font-size: 14px }
</style>
<body>
<center>
<p> ${requestScope['upload.message'] }</p>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.v512.upload.UploadServlet</servlet-class>
<init-param>
<param-name>savePath</param-name>
<param-value>luowei</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/servlet/uploadFile</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
依赖的jar包
example2
//使用FileUpload和io实现文件的上传。
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@SuppressWarnings( { "deprecation", "unchecked" })
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 防止乱码
request.setCharacterEncoding("UTF-8");
// 文件上传的出发点
DiskFileItemFactory factory = new DiskFileItemFactory();
String path = request.getRealPath("/upload");// 获取发布以后的指定路径。
factory.setRepository(new File(path));// 超过指定的大小就临时存放在硬盘(指定目录)中。
factory.setSizeThreshold(1024 * 1024);// 如果上传文件不超过10k就存放在内存中。
// 真正用来处理上传文件的。
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// 非常复杂的一个方法,真正完成上传的处理。
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
// 判断是否是file类型与非file类型的方法。
if (item.isFormField()) {
String fieldName = item.getFieldName();
String fieldContent = item.getString("UTF-8");// 防止乱码
request.setAttribute(fieldName, fieldContent);
} else {
String fieldName = item.getFieldName();
// 当FileItem是一个file的时候可以使用getName()方法去获取上传文件的路径。
String filePath = item.getName();
// 获取文件的名称(符合所有浏览器),有些浏览器会直接获取文件的名称,有些会获取路径。
int i = filePath.lastIndexOf("\\");
String fileName = filePath.substring(i + 1);
request.setAttribute(fieldName, fileName);
// InputStream is = item.getInputStream();
// byte[] b = new byte[1024];
// int bs = 0;
// OutputStream os = new FileOutputStream(path + "/" +
// fileName);
// while ((bs = is.read(b)) > 0) {
// os.write(b, 0, bs);
// }
// is.close();
// os.close();
// write()操作更方便(可以完全替代上面注意的操作)
item.write(new File(path + "/" + fileName));
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
// 跳转到指定的页面
request.getRequestDispatcher("/upload/result2.jsp").forward(request,
response);
}
}