最近写东西设计到把图片上传到服务器端保存,并且要可以对图片进行删除操作,在网上查找了好久,发现很多都不是博客形式的,都是要胡斐下载demo的,五个人觉得这也不是什么十分复杂的功能,于是就话费三天研究写了这个小demo,并且分享出来供大家参考。
本demo没有使用任何的框架结构,主要使用servlet+c3p0+maven的形式实现
首先把项目结构粘出来
其次是使用到的jar包,也就是maven 管理的jar
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>edu.cc</groupId>
<artifactId>img_up_down</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>img_up_down Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- Servlet API -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
<dependency>
<groupId>com.mchange</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.5.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>img_up_down</finalName>
</build>
</project>
主要有两个不同的包,其他的和普通的web 项目一样
第一个commons-fileupload包用于上传和下载
第二个commons-io是io 工具的类库
接下来就是代码功能实现
由于代码里注释写的较为详细就不做过多解释
数据库结构
CREATE TABLE `image_test` (
`id` int(15) NOT NULL AUTO_INCREMENT,
`p_image` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=27 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
实体类
package domain;
import lombok.Data;
@Data//lombok自动生成set,get,toString方法
public class Imgpojo {
private Integer id;
private String p_image;
}
c3p0数据库连接类和c3p0 配置文件
package dao;
import java.sql.Connection;
import java.sql.SQLException;
import org.junit.Test;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* @author chunchun
*@date 2020年5月27日
* @projectname img_up_down
*/
//shift+alt+j
public class C3P0conn {
static ComboPooledDataSource datasource = new ComboPooledDataSource("mysql");
//@Test
public Connection getConnection() throws SQLException {
return datasource.getConnection();
}
public void realse(Connection conn) {
try {
if(conn!=null && conn.isClosed()){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<named-config name="mysql">
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/zhihui?useSSL=false&serverTimezone=UTC</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
<property name="maxStatements">200</property>
</named-config>
</c3p0-config>
下面是imgdao 类用于实现增查删功能
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import domain.Imgpojo;
/**
* @author chunchun
*@date 2020年5月27日
* @projectname img_up_down
*/
//业务实现
public class Imgdao {
private C3P0conn c3p0pool = new C3P0conn();
//增加图片
//传入图片的地址,把地址存储到数据库
public void insert_img(String imgPath) throws SQLException {
String sql = "INSERT INTO image_test(id,p_image) VALUES(null,?)";
Connection conn = c3p0pool.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, imgPath);
ps.executeUpdate();
// System.out.println(temp);
c3p0pool.realse(conn);
}
//删除图片,传入图片id,根据id删除图片
public void delete_img(Integer id) throws SQLException {
String sql = "delete from image_test where id=?";
Connection conn = c3p0pool.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
int temp = ps.executeUpdate();
System.out.println(temp);
c3p0pool.realse(conn);
}
//查看图片
public ArrayList<Imgpojo> select_img() throws SQLException{
ArrayList<Imgpojo> list= new ArrayList<Imgpojo>();
String sql = "select * from image_test";
Connection conn = c3p0pool.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
while(rs.next()) {
Imgpojo img = new Imgpojo();
img.setId(rs.getInt("id"));
img.setP_image(rs.getString("p_image"));
list.add(img);
}
return list;
}
}
下面就是具体业务功能
package servlet;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
import dao.Imgdao;
import domain.Imgpojo;
/**
* @author chunchun
*@date 2020年5月27日
* @projectname img_up_down
*/
//上传图片servlet
@WebServlet("/upload")
public class UploadServlet extends HttpServlet{
Imgdao imgdao = new Imgdao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse responce) throws ServletException, IOException {
String photepath= request.getContextPath()+"/images/";
// 创建上传所需要的两个对象
DiskFileItemFactory factory = new DiskFileItemFactory(); // 磁盘文件对象
ServletFileUpload sfu = new ServletFileUpload(factory); // 文件上传对象
// 设置解析文件上传中的文件名的编码格式
sfu.setHeaderEncoding("utf-8");
// 创建 list容器用来保存 表单中的所有数据信息
List<FileItem> items = new ArrayList<FileItem>();
// 将表单中的所有数据信息放入 list容器中
try {
items = sfu.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
// 遍历 list容器,处理 每个数据项 中的信息
for (FileItem item : items) {
String name = handleFileField(item,photepath);
if(!(name==null)) {
try {
imgdao.insert_img(name);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Imgdao imgdao = new Imgdao();
try {
ArrayList<Imgpojo> list = imgdao.select_img();
request.setAttribute("list",list);
request.getRequestDispatcher("list.jsp").forward(request, responce);
} catch (SQLException e) {
e.printStackTrace();
}
}
//把图片保存到项目路径下的images文件夹
private String handleFileField(FileItem item,String repath) {
// 获取 文件数据项中的 文件名
String fileName = item.getName();
// 判断 此文件的文件名是否合法
if (fileName==null || "".equals(fileName)) {
return null;
}
// 控制只能上传图片
if (!item.getContentType().startsWith("image")) {
return null;
}
// 获取 当前项目下的 /files 目录的绝对位置
String path = "D:\\Users\\asus.DESKTOP-9D7DVCG\\eclipse-workspace2\\img_up_down\\src\\main\\webapp\\images";
File file = new File(path); // 创建 file对象
// 创建 /files 目录
if (!file.exists()) {
file.mkdir();
}
// 将文件保存到服务器上(UUID是通用唯一标识码,不用担心会有重复的名字出现)
String imgname = UUID.randomUUID()+"_"+fileName;
try {
item.write(new File(file.toString(), imgname));
} catch (Exception e) {
e.printStackTrace();
}
return repath+imgname;
}
}
UploadServlet 用于把图片上传到服务器并把具体路径保存到 数据库使用UUID唯一标识码防止文件重名
package servlet;
import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.Imgdao;
//删除图片servlet
import domain.Imgpojo;
/**
* @author chunchun
*@date 2020年5月27日
* @projectname img_up_down
*/
@WebServlet("/deleteimg")
public class DeleteingServlet extends HttpServlet{
Imgdao imgdao = new Imgdao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("pid");//图片id
System.out.println(id);
String pname = req.getParameter("imgname");//图片路径
System.out.println(pname);
// 15
// /img_up_down/images/9087b5fc-c867-4bdc-85ca-6e48ee7da9a8_ManWei01.jpg
Integer pid = Integer.parseInt(id);
try {
//删除数据库路径记录
imgdao.delete_img(pid);
} catch (SQLException e) {
e.printStackTrace();
}
//组装要删除图片的路径
String path = req.getSession().getServletContext().getRealPath("");
System.out.println(path);//D:\apache-tomcat-9.0.16\wtpwebapps\img_up_down\
String [] str =pname.split("/",3);
//System.out.println(str[2]);// images/9087b5fc-c867-4bdc-85ca-6e48ee7da9a8_ManWei01.jpg
String imgpath = str[2].replaceAll("/", "\\\\");
//System.out.println(str[2].replaceAll("/", "\\\\"));// images\9087b5fc-c867-4bdc-85ca-6e48ee7da9a8_ManWei01.jpg
String deletepath = path +imgpath;//D:\apache-tomcat-9.0.16\wtpwebapps\img_up_down\images\9087b5fc-c867-4bdc-85ca-6e48ee7da9a8_ManWei01.jpg
File file = new File(deletepath);
//判断文件是否存在
if (file.exists() == true){
System.out.println("图片存在,可执行删除操作");
Boolean flag = false;
flag = file.delete();
if (flag){
System.out.println("成功删除图片"+file.getName());
}else {
System.out.println("删除失败");
}
}else {
System.out.println("图片不存在,终止操作");
}
Imgdao imgdao = new Imgdao();
try {
ArrayList<Imgpojo> list = imgdao.select_img();
req.setAttribute("list",list);
req.getRequestDispatcher("list.jsp").forward(req, resp);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
package servlet;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.Imgdao;
import domain.Imgpojo;
//查询图片servlet
/**
* @author chunchun
*@date 2020年5月27日
* @projectname img_up_down
*/
@WebServlet("/select")
public class SelectImgServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
//request.setCharacterEncoding("utf-8");
Imgdao imgdao = new Imgdao();
try {
ArrayList<Imgpojo> list = imgdao.select_img();
//System.out.println(list.toString());
//System.out.println(list.size());
//System.out.println(list.get(0).getP_image());
request.setAttribute("list",list);
request.getRequestDispatcher("list.jsp").forward(request, resp);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
接下来就是两个承载功能的jsp页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%String ctxPath=request.getContextPath(); %>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!--
enctype="multipart/form-data"属性
text/plain ---纯文本传输,不能用于上传文件
application/x-www-form-urlencoded ---默认值,作用是设置表单传输的编码,不能用于上传文件
multipart/form-data ---制定传输数据的特殊类型,上传的非文本的内容,比如图片或是是mp3
-->
<form action="<%=ctxPath%>/upload" method="post" enctype="multipart/form-data">
<input type="file" name="images">
<button type="submit" name="upload">上传</button>
</form>
</body>
</html>
<%@page import="domain.Imgpojo"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String ctxPath = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>图片展示</title>
<script type="text/javascript">
</script>
</head>
<body>
<div align="center"><a href="index.jsp">添加</a></div>
<form action="" method="post">
<table laign="center" border="2px">
<tr>
<td>图片列表</td>
</tr>
<tr align="center">
<td>图片编号</td>
<td>图片</td>
<td>操作</td>
</tr>
<%
ArrayList<Imgpojo> list = (ArrayList<Imgpojo>)request.getAttribute("list");
%>
<%
for (int i = 0; i < list.size(); i++)
{
%>
<tr align="center">
<td><%=list.get(i).getId()%></td>
<td><img src="<%=list.get(i).getP_image()%>"></td>
<td>
<a href="<%=ctxPath%>/deleteimg?pid=<%=list.get(i).getId()%>&imgname=<%=list.get(i).getP_image() %>">删除</a>
</td>
</tr>
<%
}
%>
</table>
</form>
</div>
</body>
</html>
效果图如下
上传页面
添加
删除
项目在github 地址:https://github.com/zzc-2180886679/IMG-demo
- 到此本文结束,蟹蟹阅读希望对你有帮助*