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.完成

Servlet实现图片文件上传的更多相关文章

  1. springmvc图片文件上传接口

    springmvc图片文件上传 用MultipartFile文件方式传输 Controller package com.controller; import java.awt.image.Buffer ...

  2. 使用jsp/servlet简单实现文件上传与下载

    使用JSP/Servlet简单实现文件上传与下载    通过学习黑马jsp教学视频,我学会了使用jsp与servlet简单地实现web的文件的上传与下载,首先感谢黑马.好了,下面来简单了解如何通过使用 ...

  3. SpringMvc MultipartFile 图片文件上传

    spring-servlet.xml <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <bean id="multipar ...

  4. .Net Core 图片文件上传下载

    当下.Net Core项目可是如雨后春笋一般发展起来,作为.Net大军中的一员,我热忱地拥抱了.Net Core并且积极使用其进行业务的开发,我们先介绍下.Net Core项目下实现文件上传下载接口. ...

  5. 【Demo Project】AjaxSubmit+Servlet表单文件上传和下载

    一.背景 前段时间公司要求我做一个上传和下载固件的页面,以备硬件产品在线升级,现在我把这部分功能抽取出来作为一个Demo Project给大家分享. 话不多说,先看项目演示 --> 演示  源码 ...

  6. commons-fileload图片文件上传工具 , servlet文件图片上传案列

    本案列是java  maven工程小项目,提供个大家学习! 1.在pom.xml文件中导入依赖: <!--文件上传依赖--><dependency> <groupId&g ...

  7. SpringMvc commons-fileupload图片/文件上传

    简介 SpringMvc文件上传的实现,是由commons-fileupload这个jar包实现的. 需求 在修改商品页面,添加上传商品图片功能. Maven依赖包 pom.xml <!-- 文 ...

  8. Demo:servlet实现图片的上传

    一个简单的servlet例子,实现图片的上传功能,上传的图片给 ?HttpServletResponse 对象 public class BackGroundLogoServlet extends H ...

  9. spring boot:实现图片文件上传并生成缩略图(spring boot 2.3.1)

    一,为什么要给图片生成缩略图? 1, 用户上传的原始图片如果太大,不能直接展示在网站页面上, 因为不但流费server的流量,而且用户打开时非常费时间, 所以要生成缩略图. 2,服务端管理图片要注意的 ...

随机推荐

  1. Oracle数据库的坑

    Oracle数据库爬过的坑 ORA-00918 未定义明确列 ORA-01861: 文字与格式字符串不匹配 DPI-1005 : unable to acquire Oracle environmen ...

  2. 【转载】 自动化机器学习(AutoML)之自动贝叶斯调参

    原文地址: https://blog.csdn.net/linxid/article/details/81189154 ---------------------------------------- ...

  3. Facebook libra白皮书

    https://libra.org/en-US/white-paper/ An Introduction to Libra Libra的使命是建立一个简单的全球货币和金融基础设施,为数十亿人服务.该文 ...

  4. iOS 当键盘覆盖textFiled时简单的处理方法

    //方法1--- - (void)textFieldDidBeginEditing:(UITextField *)textField { if (iPhone5) { return; } else { ...

  5. ClientDataSet中修改,删除,添加数据和Delta属性

    ClientDataSet中使用Post提交变更的数据时,实际上并没有更新到后端数据库中,而是提交到了由DataSnap管理的数据缓冲区中.当使用了ClientDataSet.ApplyUpDates ...

  6. myeclipse安装activiti-designer

    将压缩包中的features和plugins放到dropins下,然后重启myeclipse activiti-designer下载地址: 链接:https://pan.baidu.com/s/19u ...

  7. Windows服务操作帮助类

    /// <summary> /// 打开系统服务 /// </summary> /// <param name="serviceName">系统 ...

  8. Linux中查找最耗CPU的Java代码问题

    第一步: 查看消耗CPU最高的进程PID [lolaage@web2 tomcat-ns]$ top top - 13:23:32 up 42 days, 19:11,  3 users,  load ...

  9. ConcurrentHashMap能完全替代HashTable吗?

    至此你应该能够明白,ConcurrentHashMap与HashTable都可以用于多线程的环境,但是当Hashtable的大小增加到一定的时候,性能会急剧下降,因为迭代时需要被锁定很长的时间.因为C ...

  10. todo---ezmorph

    todo---ezmorph