Java-Web 制作图片上传存储查询页面(通过Fileupload类)
作者:互联网
功能:实现图片上传的功能(限制格式和大小),然后存储和展示
一、前端上传页面
<html>
<head>
<title>$Title$</title>
</head>
<body>
<%-- 两个报错提示 --%>
<c:if test="${not empty picSuffix}">
<p>只能上传:"${picSuffix}"</p>
</c:if>
<c:if test="${not empty sizeMsg}">
<p>${sizeMsg}</p>
</c:if>
<c:remove var="picSuffix"/>
<c:remove var="sizeMsg"/>
<form action="fileUploadServlet" enctype="multipart/form-data" method="post">
<%-- enctype标注这是一个用于上传的表单 --%>
<input type="text" name="uname">
<input type="file" name="file">
<input type="submit" value="提交">
</form>
</body>
</html>
二、业务处理servlet类
@WebServlet("/fileUploadServlet")
public class FileUploadServlet extends HttpServlet {
@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 {
req.setCharacterEncoding("utf-8");
HttpSession session = req.getSession();
//要解析带有文件的request对象,需要ServletFileUpload对象。首先就要创建一个Disk工厂对象来生产ServletFileUpload对象
DiskFileItemFactory itemFactory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(itemFactory);
try {
//设置可上传的文件大小
fileUpload.setSizeMax(1024 * 10);
//1.拿到表单信息 拿到结果(返回一个list,将表单里面的每一个key和value封在FileItem对象里,一个FileItem对应一个键对值)
List<FileItem> fileItemList = fileUpload.parseRequest(req);
//1.1. 定义图片后缀数组
String[] suffixArr = {".jpg", ".jpeg", ".png", ".gif"};
//2.遍历结果集合
for (FileItem fileItem : fileItemList) {
//2.1在遍历过程中找出有文件的那个FileItem
if (!fileItem.isFormField()) {//isFormField()是否是普通的表单字段,结果是一个布朗值
String fieldName = fileItem.getFieldName();//获取键对值的key
String fieldValue = fileItem.getName();//获取文件名
//2.2从文件名中截取后缀
String suffix = fieldValue.substring(fieldValue.lastIndexOf("."));
//2.3 判断文件后缀是否符合规则 为了方便,数组转集合好使用contain
List<String> suffixList = Arrays.asList(suffixArr);
if (!suffixList.contains(suffix)) {
//2.4 如果不符合,返回一个消息
session.setAttribute("picSuffix", suffixList);
resp.sendRedirect("index.jsp");
return;
} else {//3. 如果符合,将图片存储
//3.1获取图片存储文件夹地址
String realPath = req.getRealPath("/upload");
//3.2为图片生成随机文件名
String uuidName = UUID.randomUUID().toString().replace("-", "") + suffix;
//3.3创建目录(判断目录是否存在,没有就创建)
File file = new File(realPath);
if (!file.exists()) {
file.mkdir();
}
//3.4 写入
File writeFile = new File(realPath, uuidName);//第一个参数是父目录,第二个是子目录
fileItem.write(writeFile);
//4 把文件名存到数据库中
String sql = "insert into pic_database(picName) values(?)";
DBUtil.curd(sql, uuidName);//调用封装好的工具类
}
} else {//普通字段
String fieldName = fileItem.getFieldName();
String fieldValue = fileItem.getString();//获取字段内容
}
}
} catch (SizeLimitExceededException e) {
session.setAttribute("sizeMsg", "可上传的图片大小为:" + fileUpload.getSizeMax() / 1024 + "KB");
resp.sendRedirect("index.jsp");
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
System.out.println("io流错误");
e.printStackTrace();
}
}
}
三、前端展示页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
//获取图片存储文件夹地址
String realPath = request.getContextPath()+"/upload/";
List<Picture> pictureList = new ArrayList<>();
//连接数据库,查询出所有的图片ID和名字,然后装进pictureList集合中
Connection conn = DBUtil.newInstance();
String sql = "select * from pic_database";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next()){
Picture picture = new Picture();
picture.setId(rs.getInt(1));
picture.setPic(rs.getString(2));
pictureList.add(picture);
}
//将集合存储到session中
session.setAttribute("pictureList",pictureList);
%>
<%-- 遍历域中存储的集合,并将其以图片的形式展示出来 --%>
<c:forEach items="${pictureList}" var="picture">
<img src="<%=realPath%>${picture.pic}" alt="" width="280px" height="280px" border="1px">
</c:forEach>
</body>
</html>
其他、图片实体类
public class Picture {
private int id;
private String pic;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
}
效果展示
标签:Web,req,Java,String,pic,Fileupload,new,public,fileItem 来源: https://blog.csdn.net/m0_51709303/article/details/112254957