1.首先要导入以下两个jar包:

commons-fileupload-1.2.1.jar
commons-io-1.4.jar

2.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>文件上传</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>
表单/带文件
<br>
<!-- application/x-www-form-urlencoded只有字符串的表单 -->
<form action="${pageContext.request.contextPath}/UploadPictureServlet" method="post" enctype="multipart/form-data"> 文件名
<input type="text" name="filename">
<br />
文件
<input type="file" name="file">
<br />
<input type="submit" value="提交">
</form>
</body>
</html>

3.Servlet文件:

  package com.pearl.util;

  1 import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID; 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 UploadPictureServlet extends HttpServlet { public void destroy() {
super.destroy();
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { try {
// ① 创建ServletFileUpload实例
DiskFileItemFactory factory = new DiskFileItemFactory(); String realPath = getServletContext().getRealPath("/");
// // 【设置缓存目录】
factory.setRepository(new File(realPath));
ServletFileUpload upload = new ServletFileUpload(factory);
// ② 创建DiskFileItemFactory
// ③ 解析request获取List<FileItem>
// 【表单大小总和】
upload.setSizeMax(1024 * 1024 * 60);
// 【单个文件不得超过】
upload.setFileSizeMax(1024 * 1024 * 20);
// 【处理中文乱码】
upload.setHeaderEncoding("UTF-8");
if (upload.isMultipartContent(request)) {// 判断是否为带文件表单 <form
// enctype="multipart/form-data"
List<FileItem> list = upload.parseRequest(request);
for (FileItem item : list) {
// 文本或文件
if (item.isFormField()) {
// 文本字段
// 获取变量名
String key = item.getFieldName();// 表单字段的变量名
String value = item.getString("UTF-8");// 表单字段的输入值
System.out.println(key);
System.out.println(value);
} else {
// 文件
// 文件类型
// text/plain .txt
// image/png .png
// image/bmp .bmp
String contentType = item.getContentType();
// 文件名
String fileName = item.getName();// 表单的输入框值
// 变量名
String name = item.getFieldName();// 表单的变量名
// 文件 内容
String content = item.getString();
// 二进制文件
InputStream input = item.getInputStream();
System.out.println(contentType);
System.out.println(fileName);
System.out.println(name);
//System.out.println(content);
System.out.println(input); // ① 服务端目录 (服务端真实路径)
String dir = getServletContext().getRealPath("/upload");
System.out.println(dir);
// ② 文件名冲突
if (fileName.contains("/")) {
fileName = fileName.substring(name.lastIndexOf("/") + 1);
System.out.println(fileName);
}
// (添加前缀 唯一字符串, 时间毫秒值 UUID随机产生全球唯的id)
String path = UUID.randomUUID().toString() + "#" + fileName; // ③ 写入File对象
File driSave = new File(dir);
if (!driSave.exists()) {
driSave.mkdir();
}
File saveFile = new File(dir, path); if (!saveFile.exists()) {
saveFile.createNewFile();
}
System.out.println(saveFile.getAbsolutePath());
item.write(saveFile);
// 删除临时文件
item.delete();
input.close();
} }
} else {
System.out.println("表单不存在文件");
}
// ④ 循环显示内容FileItem
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} public void init() throws ServletException { } }

4.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>
<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>UploadPictureServlet</servlet-name>
<servlet-class>com.pearl.util.UploadPictureServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>UploadPictureServlet</servlet-name>
<url-pattern>/UploadPictureServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

5.完成

最新文章

  1. react-native 简单的导航
  2. 如何让两个div在同一行显示?一个float搞定
  3. Vmware玩mac os x分享
  4. div隐藏
  5. servlet中获取request中文乱码问题分析
  6. web-请求无缓存
  7. 配置linux中文
  8. UVA10487(二分)
  9. Java中的工具类和新特性
  10. IceMx.Mvc
  11. Android--paint应用举例
  12. NOI2004 郁闷的出纳员 Splay
  13. 关键词匹配(Ac自动机模板题)
  14. 如何搭建个人博客网站(Mac)
  15. Spring Web MVC(二)
  16. Apache No installed service named &quot;Apache2.4&quot;的解决办法
  17. openblas下载安装编译
  18. 线段树及Lazy-Tag
  19. 【DB2】Event monitor for locking
  20. 微信小程序可以转发给微信好友了

热门文章

  1. SQL-W3School-测验:SQL 测验
  2. Ionic4.x Javascript 扩展 ActionSheet Alert Toast Loading 以及 ionic 手势相 关事件
  3. PorterDuffXfermode之PorterDuff.Mode.MULTIPLY
  4. [Java复习] 分布式PRC - Dubbo
  5. Spring Cloud Eureka集群部署到Linux环境
  6. CRM-项目记录
  7. 一种可以避免数据迁移的分库分表scale-out扩容模式
  8. 浅谈service、DAO层引入(转)
  9. LODOP打印超文本字符串拼接1 固定表格填充数值
  10. charles 工具菜单总结