今天闲着没事,整理了一下Servlet中文件上传的代码,用到的是Apache的commons-fileupload组件,和大家分享一下。
废话不多说了,直接进入正题。
首先是导入对应的两个文件上传用到的jar包commons-fileupload-1.2和commons-io-1.3.2,这个Apache官方网站上可以下到。完成后如下:
Servlet类中文件上传的代码:
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.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class test extends HttpServlet {
/**
* 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 {
//设置编码格式
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//得到文件要上传的文件夹路径,此例子是在工程的photo文件夹下
String path = this.getServletContext().getRealPath("photo");
//实例化文件工厂
DiskFileItemFactory dff = new DiskFileItemFactory();
//设置其大小
dff.setSizeThreshold(1024 * 1024 * 10);
//文件上传类
ServletFileUpload sfu = new ServletFileUpload(dff);
//设置其大小
sfu.setSizeMax(1024 * 1024 * 10);
try {
//从页面得到所有有请求集合
List list = sfu.parseRequest(request);
//迭代该集合
Iterator it = list.iterator();
//如果请求中有元素
while (it.hasNext()) {
//将其转化为FileItem对像
FileItem fi = (FileItem) it.next();
//如果是普通请求对像
if (fi.isFormField()) {
//得到该请求的请求体名称并输出
String name = fi.getString("utf-8");
System.out.println(name);
//否则即是要上传的文件
} else {
//设置该文件的具体上传路径和文件名
File f = new File(path + "\\" + fi.getName());
//如果该文件存在
if(f.exists()){
response.getWriter().println("文件名已存在
!");
return;、
}
//不存在就上传文件
fi.write(f);
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
前端测试页面代码:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"
contentType="text/html;charset=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>
<img src="photo/img20.jpg" width="100" height="100">
<br>
<form action="test" method="post" enctype="multipart/form-data">
<input type="text" name="name">
<br>
<input type="text" name="password">
<br>
<input type="file" name="file">
<br>
<input type="submit" value="sssdf">
<br>
</form>
</body>
</html>
web.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.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>test</servlet-name>
<servlet-class>test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
到此文件上传程序结束。
废话不多说了,直接进入正题。
首先是导入对应的两个文件上传用到的jar包commons-fileupload-1.2和commons-io-1.3.2,这个Apache官方网站上可以下到。完成后如下:
Servlet类中文件上传的代码:
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.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class test extends HttpServlet {
/**
* 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 {
//设置编码格式
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//得到文件要上传的文件夹路径,此例子是在工程的photo文件夹下
String path = this.getServletContext().getRealPath("photo");
//实例化文件工厂
DiskFileItemFactory dff = new DiskFileItemFactory();
//设置其大小
dff.setSizeThreshold(1024 * 1024 * 10);
//文件上传类
ServletFileUpload sfu = new ServletFileUpload(dff);
//设置其大小
sfu.setSizeMax(1024 * 1024 * 10);
try {
//从页面得到所有有请求集合
List list = sfu.parseRequest(request);
//迭代该集合
Iterator it = list.iterator();
//如果请求中有元素
while (it.hasNext()) {
//将其转化为FileItem对像
FileItem fi = (FileItem) it.next();
//如果是普通请求对像
if (fi.isFormField()) {
//得到该请求的请求体名称并输出
String name = fi.getString("utf-8");
System.out.println(name);
//否则即是要上传的文件
} else {
//设置该文件的具体上传路径和文件名
File f = new File(path + "\\" + fi.getName());
//如果该文件存在
if(f.exists()){
response.getWriter().println("文件名已存在
!");
return;、
}
//不存在就上传文件
fi.write(f);
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
前端测试页面代码:
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"
contentType="text/html;charset=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>
<img src="photo/img20.jpg" width="100" height="100">
<br>
<form action="test" method="post" enctype="multipart/form-data">
<input type="text" name="name">
<br>
<input type="text" name="password">
<br>
<input type="file" name="file">
<br>
<input type="submit" value="sssdf">
<br>
</form>
</body>
</html>
web.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.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>test</servlet-name>
<servlet-class>test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
到此文件上传程序结束。