目录
前言
继上篇博客
文件上传
由于我们在上篇已经生成了带图片属性的接口、实体以及配置文件。所以我们就不需要重新逆向生成mapper和model包中的代码了
导入依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
配置文件上传解析器
<!-- 处理文件上传下载问题-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 文件最大大小(字节) 1024*1024*50=50M-->
<property name="maxUploadSize" value="52428800"></property>
<!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
<property name="resolveLazily" value="true"/>
</bean>
配置存放地址
导入PropertiesUtil工具类
package com.xiaoxu.utis;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesUtil {
public static String getValue(String key) throws IOException {
Properties p = new Properties();
InputStream in = PropertiesUtil.class.getResourceAsStream("/resource.properties");
p.load(in);
return p.getProperty(key);
}
}
编写resource.properties
dir=D:/temp2/upload/
server=/upload/
添加sql
<select id="selectPage" resultType="com.xiaoxu.model.Bookxx" parameterType="com.xiaoxu.model.Bookxx" >
select
<include refid="Base_Column_List" />
from t_hibernate_book
<where>
<if test="book_name != null">
and book_name like concat('%',#{book_name},'%')
</if>
</where>
</select>
编写PageController类
package com.xiaoxu.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author小徐
* @site www.veryedu.cn
* @company xu集团
* @create 2023-09-07 17:27
*
* 用来处理页面跳转
*/
@Controller
public class PageController {
@RequestMapping("/page/{page}")
public String toPage(@PathVariable("page") String page){
return page;
}
@RequestMapping("/page/{dir}/{page}")
public String toDirPage(@PathVariable("dir") String dir,
@PathVariable("page") String page){
return dir + "/" + page;
}
}
编写主页展示界面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://jsp.veryedu.cn" prefix="z"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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">
<link
href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.css"
rel="stylesheet">
<script
src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.0/js/bootstrap.js"></script>
<title>博客列表</title>
<style type="text/css">
.page-item input {
padding: 0;
width: 40px;
height: 100%;
text-align: center;
margin: 0 6px;
}
.page-item input, .page-item b {
line-height: 38px;
float: left;
font-weight: 400;
}
.page-item.go-input {
margin: 0 10px;
}
</style>
</head>
<body>
<form class="form-inline"
action="${pageContext.request.contextPath }/clz/list" method="post">
<div class="form-group mb-2">
<input type="text" class="form-control-plaintext" name="book_name"
placeholder="请输入书籍名称">
<!-- <input name="rows" value="20" type="hidden"> -->
<!-- 不想分页 -->
</div>
<button type="submit" class="btn btn-primary mb-2">查询</button>
<a class="btn btn-primary mb-2" href="${pageContext.request.contextPath }/clz/preSave">新增</a>
</form>
<table class="table table-striped ">
<thead>
<tr>
<th scope="col">书籍编号</th>
<th scope="col">书籍图片</th>
<th scope="col">价格</th>
<th scope="col">image</th>
<th scope="col">操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="b" items="${list }">
<tr>
<td>${b.book_id }</td>
<td>${b.book_name }</td>
<td>${b.price }</td>
<td>
<img src="${b.image}" style="height: 100px;width: 60px">
</td>
<td>
<a href="${pageContext.request.contextPath }/clz/preSave?book_id=${b.book_id}">修改</a>
<a href="${pageContext.request.contextPath }/clz/del/${b.book_id}">删除</a>
<a href="${pageContext.request.contextPath }/page/clz/upload?book_id=${b.book_id}">图片上传</a>
<a href="${pageContext.request.contextPath }/clz/download?book_id=${b.book_id}">图片下载</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<!-- 这一行代码就相当于前面分页需求前端的几十行了 -->
<z:page pageBean="${pageBean }"></z:page>
${pageBean }
</body>
</html>
编写文件上传方法
// 文件上传
@RequestMapping("/upload")
public String upload(Bookxx bookxx ,MultipartFile xxx){
try {
// 上传图片真实存放地址
String dir = PropertiesUtil.getValue("dir");
// 网络访问地址
String server = PropertiesUtil.getValue("server");
String filename = xxx.getOriginalFilename();FileUtils.copyInputStreamToFile(xxx.getInputStream(),new File(dir+filename));
//保存
bookxx.setImage(server+filename);
bookxxBiz.updateByPrimaryKeySelective(bookxx);
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:list";
}
搭建一个图片上传的操作页面
<%--
Created by IntelliJ IDEA.
User: 86155
Date: 2023/9/9
Time: 14:55
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>w
<html>
<head>
<title>书籍logo上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/clz/upload" method="post" enctype="multipart/form-data">
<label>书籍编号:</label><input type="text" name="book_id" readonly="readonly" value="${param.book_id}"/><br/>
<label>书籍图片:</label><input type="file" name="xxx"/><br/>
<input type="submit" value="上传图片"/>
</body>
</html>
文件下载
在Controller层中加入以下代码,如下:
@RequestMapping("/download")
public ResponseEntity<byte[]> download(Bookxx bookxx,HttpServletRequest req){
try {
//先根据文件id查询对应图片信息
Bookxx bookxx1 = this.bookxxBiz.selectByPrimaryKey(bookxx.getBook_id());
String diskPath = PropertiesUtil.getValue("dir");
String reqPath = PropertiesUtil.getValue("server");
String realPath = bookxx1.getImage().replace(reqPath,diskPath);
String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
//下载关键代码
File file=new File(realPath);
HttpHeaders headers = new HttpHeaders();//http头信息
String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
headers.setContentDispositionFormData("attachment", downloadFileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//MediaType:互联网媒介类型 contentType:具体请求中的媒体类型信息
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
多文件上传
多文件上传跟单文件上传的区别
多文件上传和单文件上传的区别在于,多文件上传可以同时上传多个文件,而单文件上传只能上传一个文件。在实际应用中,多文件上传通常适用于需要同时上传多个文件的场景,比如上传多张图片、多个文档等;而单文件上传则适用于只需要上传一个文件的场景,比如上传头像、上传附件等。多文件上传通常要使用专门的插件或工具库来实现,比如jQuery File Upload、Dropzone.js等。
在Controller层中加入以下代码,如下:
@RequestMapping("/uploads")
public String uploads(HttpServletRequest req, Bookxx clazz, MultipartFile[] files){
try {
StringBuffer sb = new StringBuffer();
for (MultipartFile cfile : files) {
//思路:
//1) 将上传图片保存到服务器中的指定位置
String dir = PropertiesUtil.getValue("dir");
String server = PropertiesUtil.getValue("server");
String filename = cfile.getOriginalFilename();
FileUtils.copyInputStreamToFile(cfile.getInputStream(),new File(dir+filename));
sb.append(filename).append(",");
}
System.out.println(sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:list";
}
效果展示
jrebel的使用
jrebel的好处
多文件上传跟单文件上传的区别
多文件上传和单文件上传的区别在于,多文件上传可以同时上传多个文件,而单文件上传只能上传一个文件。在实际应用中,多文件上传通常适用于需要同时上传多个文件的场景,比如上传多张图片、多个文档等;而单文件上传则适用于只需要上传一个文件的场景,比如上传头像、上传附件等。多文件上传通常要使用专门的插件或工具库来实现,比如jQuery File Upload、Dropzone.js等。
jrebel的好处
JRebel是一个Java开发工具,它提供了一种在开发过程中实时更新和重新加载Java代码的能力,而无需重新启动应用程序或重新部署。以下是JRebel的一些好处:
快速代码更新:JRebel允许开发人员在修改代码后立即看到变化的效果,无需重新编译和部署整个应用程序,从而提高了开发效率。
减少重启时间:传统的Java开发过程中,每次对代码进行修改后都需要重新启动应用,这会花费大量时间。而使用JRebel,可以避免重启,节省开发时间。
保持应用状态:JRebel在代码重新加载时,会尽量保持应用程序的状态,包括会话、数据库连接等,从而减少重新登录或重新建立连接的麻烦。
提高测试效率:JRebel能够加快代码更新的速度,使得开发人员可以更快地进行测试和调试,及时发现和修复问题。
支持广泛的框架和服务器:JRebel可以与多种Java框架和服务器兼容,包括Spring、Hibernate、Tomcat等,使得它可以适用于各种不同的开发环境。
总的来说,JRebel能够大大提升Java开发人员的工作效率,减少开发和调试过程中的重启时间,让开发过程更加流畅和高效。
jerbel的安装
重启后的IDEA是这样的:
但是此时我们还需要打开代理(黑窗口)才可以用jrebel启动项目。如下:
设置jrebel离线
打开代理后点击jrebel启动项目,会弹出以下窗口,具体操作如下:
1.在弹出框中Team URL下方第一个输入框输入:
http://127.0.0.1:8888/0e63ac70-2074-46d3-9de1-46fb2befde0a
2.在第二个输入框输入自己的邮箱。
3.勾选 I agree with the term...
4.最后点击最下方按钮Activete JRebel即可。
设置完jrebel离线之后,在用jrebel插件启动项目之前就可以不打开代理辅助工具了。
今天的分享就到这里了!!!!!!!!!!!