目录
一、SpringMVC支持文件下载
后端代码
package com.zking.ssm.book.controller;
import com.zking.ssm.book.model.BookFile;
import com.zking.ssm.book.service.IBookFileService;
import com.zking.ssm.book.vo.BookFileVo;
import org.apache.commons.io.FileUtils;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
@Controller
@RequestMapping("/bookFile")
public class BookFileController {
private static final String DEFAULT_PATW = "/uploads/";
@Autowired
private IBookFileService bookFileService;
//文件上传和下载的宗旨文件从哪里来(原头)放那里去(目标位置)
//原头:读 InputStriedm
/**
* 文件上传
*
* @return
*/
@RequestMapping("/upload")
public String upload(BookFileVo bookFileVo, HttpServletRequest req) {
try {
//1.将上传的图片保存到指定的位置
//获取文件对象
MultipartFile bFile = bookFileVo.getBFile();
//获取文件名
String fileName = bFile.getOriginalFilename();
//获取文件类型
String contentType = bFile.getContentType();
//获取图片路径
String path = DEFAULT_PATW + fileName;
//获取保存图片的绝对路径
String FilePath = this.transfor(path, req);
//2.将书本图片信息写入到t_book_file书本图片中
//3.根据书本编号更新对应的book_images信息
bookFileVo.setContentType(contentType);
bookFileVo.setRealName(fileName);
bookFileVo.setUrl(path);
bookFileService.insert(bookFileVo);
bFile.transferTo(new File(FilePath));
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/book/queryBookPager";
}
/**
* 就相对路径转换车绝对路径
*
* @param relatvePath 相对路径
* @return
*/
private String transfor(String relatvePath, HttpServletRequest req) {
return req.getServletContext().getRealPath(relatvePath);
}
/**
* 文件下载
*
* @return
*/
@RequestMapping("/download")
public ResponseEntity<byte[]> download(String fileId,HttpServletRequest req) {
try {
//1.根据书本图片id查询书本图片信息
BookFile bookFile = bookFileService.selectByPrimaryKey(fileId);
//2.下载书本图片
//下载关键代码
String path = this.transfor(bookFile.getUrl(), req);
File file = new File(path);
HttpHeaders headers = new HttpHeaders();//http头信息
String downloadFileName = new String(bookFile.getRealName().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 (IOException e) {
e.printStackTrace();
}
return null;
}
}
二、SpringMVC支持文件上传
1.文件上传三要素:
(1)表单的提交方式必须是POST请求
(2)表单中必须有一个文件上传项:<input type=“file” name=“upload”/>,文件上传项必须有name属性和值;
(3)表单的enctype属性的值必须是multipart/form-data
2.导入文件上传的两个jar包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
3.配置文件上传解析器
maxUploadSize参数为上传最大限制大小。
<!-- 配置文件上传解析器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="#{1024*1024*20}"></property>
<property name="defaultEncoding" value="utf-8"></property>
</bean>
4.index.jsp前端页面
<%--
Created by IntelliJ IDEA.
User: zjjt
Date: 2022/4/3
Time: 19:59
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<%@include file="/common/head.jsp"%>
</head>
<body>
<h1>s书本列表</h1>
<form action="${pageContext.request.contextPath}/book/queryBookPager" method="post">
<label>书本名称:</label> <input type="text" name="bookName"/>
<input type="submit" value="查询">
</form>
<a href="${ctx}/book/toAddBook">书本新增</a>
<table width="100%" border="1">
<tr>
<th>书本编号</th>
<th>书本名称</th>
<th>书本图片</th>
<th>书本价格</th>
<th>书本类型</th>
<th>操作</th>
</tr>
<c:forEach items="${books}" var="b">
<tr>
<th>${b.bookId}</th>
<th>${b.bookName}</th>
<th>
<c:if test="${empty b.bookImages}">
未上传图片
</c:if>
<c:if test="${not empty b.bookImages}">
<img src="${ctx}/bookFile/download?fileId=${b.bookImages}" width="200px"/>
</c:if>
</th>
<th>${b.bookPrice}</th>
<th>${b.bookType}</th>
<th>
<a href="${ctx}/book/queryBookByID?bookId=${b.bookId}&type=edit">编辑</a>
<a href="${ctx}/book/queryBookByID?bookId=${b.bookId}&type=detail">详情</a>
<a onclick="return confirm('是否删除')" href="${ctx}/book/delBook?bookID=${b.bookId}">删除</a>
<a href="${ctx}/input/book/uploadBook?bookId=${b.bookId}">上传图片</a>
<c:if test="${not empty b.bookImages}">
<a href="${ctx}/bookFile/download?fileId=${b.bookImages}">下载图片</a>
</c:if>
</th>
</tr>
</c:forEach>
</table>
${pageBean}
</body>
</html>