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. Ionic4.x Theming(主题) 增加内置主题 颜色 修改内置组件默认样式 修改底部 Tabs 背景颜色以及按钮颜色

    1.Ionic4.x Theming(主题) Ionic4.x 修改主题颜色的话需要在 src/theme/variables.scss 文件中修改. https://ionicframework.c ...

  2. angular中的动态路由

    1.配置动态路由 const routes: Routes = [ {path: 'home', component: HomeComponent}, {path: 'news', component ...

  3. Quartz.Net 学习随手记之03 配置文件

    第一种方式:直接写入代码中 NameValueCollection properties = new NameValueCollection(); properties["quartz.sc ...

  4. (十七)Centos之安装配置tomcat8

    第一步:下载Tomcat8压缩包 进入 http://tomcat.apache.org/download-80.cgi 下载tar.gz压缩包 第二步:用ftp工具把压缩包上传到/home/data ...

  5. nginx conf 文件

    server { listen ; server_name local.light.com; index index.html index.htm index.php; root /home/wwwr ...

  6. WIN 10 看不到SAMBA共享的硬盘

    1.SMB1.0/CIFS协议默认被关闭了,之前的勒索病毒就是用的这个协议的漏洞,所以你去“启动和关闭windows功能”下手动勾选启用SMB1.0/CIFS协议 2.管理员身份执行 sc.exe c ...

  7. .Net Core 常用开发工具

    组件名 描述 可选版本 推荐版本 Visual Studio Community 社区免费版 For Visual Studio 2017 For Visual Studio 2019 Visual ...

  8. Win 10环境下6sV2.1模型编译心得

    最新版本6sV2.1模型是通过FORTRAN95编写的,2017年11月代码编写完成,2018年11月发布在模型官网上.通常我们在使用过程中都是调用模型的.exe可执行文件,而下载下来的是FORTRA ...

  9. js实现随机数及随机数组

    js数组元素的随机调用 工作中网页填充数据时需要一个短语库,来拼接在短语句子后边.那就写一个js吧,放在input的keydown或keyup里边用喽. 贴代码: <SCRIPT LANGUAG ...

  10. Docker容器中用户权限管理

    在Linux系统中有一部分知识非常重要,就是关于权限的管理控制:Linux系统的权限管理是由uid和gid负责,Linux系统会检查创建进程的uid和gid,以确定它是否有足够的权限修改文件,而非是通 ...