1.文件的上传
文件上传:
客户端通过文件流上传到服务器上面 ---> Controller接收这个文件 --->再将文件写到指定的地方
到数据库中保存文件的记录。
1.1在pom.xml文件中导入依赖包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
1.2配置文件上传解析器
在resources 目录下的 applicatioContext-base.xml 中配置一个bean。
<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>
1.3数据表 t_book_file
create table t_book_file
(
file_id varchar(32) primary key comment '文件ID',
real_name varchar(50) not null comment '文件名称',
content_type varchar(50) not null comment '文件类型',
url varchar(256) not null comment '文件路径'
);
用来保存上传的文件。
在book表中加入一个字段来保存上传文件的ID,即:与file_id字段对应。
2.4controller
package com.zking.mybatisdemo.controller;
import com.zking.mybatisdemo.model.Bookfile;
import com.zking.mybatisdemo.model.FileUpload;
import com.zking.mybatisdemo.service.IBookFileService;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
/**
* @author ljl
* @site www.xiaomage.com
* @company xxx公司
* @create 2022-06-17 14:43
*/
@Controller
public class BookImageUpload {
@RequestMapping("/openUploadPage")
public String openUploadPage(){
return "book/ploadPage";
}
/*webapp下面的一个目录*/
private String upload_path="/upload/";
@Autowired
private IBookFileService bookFileService;
@PostMapping("/uploads")
public String upload(FileUpload uploadFile, HttpServletRequest request) throws IOException {
/*得到这个文件*/
MultipartFile imgFile = uploadFile.getImg();
/*获取上传文件名*/
String fname = imgFile.getOriginalFilename();
/*文件类型*/
String contentType=imgFile.getContentType();
/*文件id*/
// String fid= UUID.randomUUID().toString().replace("-" ,"");
String path =upload_path+fname;
/*获取绝对路径*/
String realPath = request.getServletContext().getRealPath(path);
File f= new File(realPath);
imgFile.transferTo(f);
//保存文件上传记录信息
Bookfile bookfile =Bookfile.builder().build();
bookfile.setBid(uploadFile.getBid());
/*文件类型*/
bookfile.setContentType(contentType);
/*文件名称*/
bookfile.setRealname(fname);
/*文件路径*/
bookfile.setUrl(path);
bookFileService.insert(bookfile);
return "redirect: /books";
}
}
实体类Book
package com.zking.mybatisdemo.model;
import lombok.Data;
import java.math.BigDecimal;
/**
* @author ljl
* @site www.xiaomage.com
* @company xxx公司
* @create 2022-06-15 19:10
*/
@Data
public class Book {
private Integer bid;
private String bname;
private BigDecimal price;
private String type;
private String fileId;
}
实体Bookfile
package com.zking.mybatisdemo.model;
import lombok.Builder;
import lombok.Data;
/**
* @author ljl
* @site www.xiaomage.com
* @company xxx公司
* @create 2022-06-17 21:32
*/
@Data
@Builder
public class Bookfile extends Book {
private String fileId;
private String realname;
private String contentType;
private String url;
}
在mapper包下相对应的接口下写方法
BookFileMapper
/**文件上传
* @param bookfile
* @return
*/
int insert(Bookfile bookfile );
BookMapper
/**修改file_id
* @param book 书本对象
* @return 执行行数
*/
int updateBookFileByBid(Book book);
sql
<insert id="insert">
insert into t_book_file(file_id,real_name,content_type,url)
values(#{fileId},#{realname},#{contentType},#{url})
</insert>
在定义一个接口
IBookfileService然后实现这个接口中的上传方法
@Service
public class BookFileService implements IBookFileService {
@Autowired
private BookMapper bookMapper;
@Autowired
private BookFileMapper bookFileMapper;
/*事务支持*/
@Transactional
@Override
public void insert(Bookfile bookfile){
String fid= UUID.randomUUID().toString().replace("-" ,"");
bookfile.setFileId(fid);
bookFileMapper.insert(bookfile);
/*先保存到上传的记录表中,在更新到书本信息中去*/
Book book =new Book();
book.setBid(bookfile.getBid());
book.setFileId(bookfile.getFileId());
bookMapper.updateBookFileByBid(book);
}
}
在数据绑定界面加入一个点击事件用来打开文件上传界面
<td>
<a href="#" onclick="del(${book.bid})">删除</a>
<a href="#" onclick="up(${book.bid})">修改</a>
<a href="<%=request.getContextPath()%>/openUploadPage?bid=${book.bid}">上传</a>
</td>
sql
<!--修改file_id-->
<update id="updateBookFileByBid">
update t_book
<set>
<if test="fileId !=null">
file_id=#{fileId}
</if>
<where>
bid=#{bid}
</where>
</set>
</update>
service
@Service
public class BookFileService implements IBookFileService {
@Autowired
private BookMapper bookMapper;
@Autowired
private BookFileMapper bookFileMapper;
/*事务支持*/
@Transactional
@Override
public void insert(Bookfile bookfile){
String fid= UUID.randomUUID().toString().replace("-" ,"");
bookfile.setFileId(fid);
bookFileMapper.insert(bookfile);
/*先保存到上传的记录表中,在更新到书本信息中去*/
Book book =new Book();
book.setBid(bookfile.getBid());
book.setFileId(bookfile.getFileId());
bookMapper.updateBookFileByBid(book);
}
}
主界面
<a href="#" onclick="del(${book.bid})">删除</a>
<a href="#" onclick="up(${book.bid})">修改</a>
<a href="<%=request.getContextPath()%>/openUploadPage?bid=${book.bid}">上传</a>
/*webapp下面的一个目录*/ private String upload_path="/upload/";
用来保存上传图片的地方
编写文件上传页面
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2022/6/17
Time: 14:46
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="<%=request.getContextPath()%>/uploads" method="post" enctype="multipart/form-data">
<%-- param.bid 表示别的页面传入的参数--%>
Id:<input type="text" name="bid" value="${param.bid}">
<input type="file" name="img">
<input type="submit" value="上传">
</form>
</body>
</html>
${param.bid}:用来绑定数据绑定界面传过来的书本id。通过书本的id在数据库中找到对应的书本。
功能实现过程:
首写我们通过点击主界面的上传按钮 根据 <%=request.getContextPath()%>/openUploadPage?bid=${book.bid}
上下文路径打开 文件上传的界面 ---》选择需要上传的文件 ---》 点击上传按钮 通过Controller控制器中定义的名为
uploads
找到
public String upload(FileUpload uploadFile, HttpServletRequest request)方法
然后得到这个文件,上传的文件名,文件类型,文件id, 获取文件的绝对路径。
在赋值到上传文件的实体中 通过set方法给每一个字段赋值,
最后通过service层调用文件上传的方法,service层在调用mapper,一步步往上调然后后执行上传文件的sql语句,把数据加入到t_book_file表中
文件上传成后我们要将t-book表中的 file_id字段修改为上传文件的id 在此我们要执行两次数据库操作所有我们要在方法中加入事务支持以此来保证数据的一致性,
/*事务支持*/ @Transactional