1.下载apache的jar包
commons-fileupload-1.2.2.jar
commons-io-2.4.jar
2.创建servlet
package com.yw.test01;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
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.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class MyFileUpdate extends HttpServlet
{
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("utf-8");
String uploadFileName = ""; // 上传的文件名
String fieldName = ""; // 表单字段元素的name属性值
// 请求信息中的内容是否是multipart类型
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
// 上传文件的存储路径(服务器文件系统上的绝对文件路径)
String uploadFilePath = request.getSession().getServletContext().getRealPath("upload/");
System.out.println("uploadFilePath=" + uploadFilePath);
boolean flag = false;
if (isMultipart)
{
FileItemFactory factory = new DiskFileItemFactory();
System.out.println("factory=" + factory);
ServletFileUpload upload = new ServletFileUpload(factory);
System.out.println("upload=" + upload);
try
{
// 解析form表单中所有文件
List<FileItem> items = upload.parseRequest(request);
System.out.println("items=" + items);
Iterator<FileItem> iter = items.iterator();
while (iter.hasNext())
{ // 依次处理每个文件
FileItem item = (FileItem) iter.next();
if (item.isFormField())
{ // 普通表单字段
fieldName = item.getFieldName(); // 表单字段的name属性值
if (fieldName.equals("user"))
{
// 输出表单字段的值
// out.print(item.getString("UTF-8") +
// "上传了文件。<br/>");
System.out.println(item.getString("UTF-8") + "上传了文件。");
}
}
else
{ // 文件表单字段
String fileName = item.getName();
if (fileName != null && !fileName.equals(""))
{
File fullFile = new File(item.getName());
File saveFile = new File(uploadFilePath, fullFile.getName());
item.write(saveFile);
uploadFileName = fullFile.getName();
// out.print("上传成功后的文件名是:" + uploadFileName);
System.out.println("上传成功后的文件名是:" + uploadFileName);
flag = true;
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
flag = false;
}
}
// response.sendRedirect("index.jsp");
if (flag)
{
String str="上传成功后的文件名是:" + uploadFileName;
request.setAttribute("message", str);
request.getRequestDispatcher("result.jsp").forward(request, response);
}
else
{
response.sendRedirect("result.jsp");
}
}
}
3.配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
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_3_0.xsd">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>MyFileUpdate</servlet-name>
<servlet-class>com.yw.test01.MyFileUpdate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyFileUpdate</servlet-name>
<url-pattern>/MyFileUpdate</url-pattern>
</servlet-mapping>
</web-app>
4.创建jsp文件
index.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>
<form action="MyFileUpdate" enctype="multipart/form-data" method="post">
<input type="file" name="upfile" /> <input type="submit">
</form>
</body>
</html>
result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page language="java" import="java.util.*"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
request.setCharacterEncoding("utf-8");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'ok.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">
<meta http-equiv="Content-Type" content="text/html;CHARSET=utf-8">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
result.jsp<br>
<p style="background-color: green;">
结果:${requestScope.message}
<p>
</body>
</html>