接着上篇SpringMVC--文件上传,只是实现了文件的上传,接着来实现文件的下载
一、准备工作
上次只是写了文件上传的接口,先把注册的接口功能实现
1. 实体类定义
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Player {
private Integer id;
private String name;
private String password;
private String nickname;
private String photo;
private String filetype;
}
2. Mapper接口和映射文件
接口:
public interface PlayerMapper {
Integer addPlayer(Player player);
}
xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aruba.mapper.PlayerMapper">
<!--Integer addPlayer(Player player);-->
<insert id="addPlayer">
insert into player
values (default, #{name}, #{password}, #{nickname}, #{photo}, #{filetype})
</insert>
</mapper>
3. Service接口和实现类
接口:
public interface PlayerService {
Integer addPlayer(Player player);
}
实现类:
@Service
@Transactional
public class PlayerServiceImpl implements PlayerService {
@Autowired
private PlayerMapper playerMapper;
@Override
public Integer addPlayer(Player player) {
return playerMapper.addPlayer(player);
}
}
4. Controller层
@Autowired
private PlayerService playerService;
@RequestMapping("registerPlayer.do")
@ResponseBody
public String register(Player player) {
System.out.println(player);
Integer rows = playerService.addPlayer(player);
if (rows != null && rows > 0)
return "success";
return "failed";
}
5. html修改
将上传图片返回结果的filetype和photo设置到两个隐藏input标签中,并在form表单上指定action为registerPlayer.do
<html>
<head>
<title>Title</title>
<script src="js/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$("#upload").click(function () {
var imgFile = $("#headImg")[0].files[0]
if (imgFile == undefined) {
alert("请选择文件")
return
}
console.log(imgFile)
var formdata = new FormData()
formdata.append("img", imgFile)
$.ajax({
type: "post",
data: formdata,
url: "uploadImg.do",
processData: false,
contentType: false,
success: function (ret) {
console.log(ret)
alert(ret.msg)
$("#head").attr("src", ret.filepath)
$("#filetypeInput").value= ret.filetype
$("#photoInput").value = ret.photo
},
xhr: function () {
var xhr = new XMLHttpRequest();
//使用XMLHttpRequest.upload监听上传过程,注册progress事件,打印回调函数中的event事件
xhr.upload.addEventListener('progress', function (e) {
//loaded代表上传了多少
//total代表总数为多少
var progressRate = (e.loaded / e.total) * 100 + '%';
//通过设置进度条的宽度达到效果
$('.progress > div').css('width', progressRate );
})
return xhr;
}
})
})
})
</script>
<style>
#head {
width: 200px;
height: 200px;
}
.progress {
width: 200px;
height: 10px;
border: 1px solid #ccc;
border-radius: 10px;
margin: 10px 0px;
overflow: hidden;
}
/* 初始状态设置进度条宽度为0px */
.progress > div {
width: 0px;
height: 100%;
background-color: yellowgreen;
transition: all .3s ease;
}
</style>
</head>
<body>
<form action="registerPlayer.do">
<p>用户名:<input type="text" name="name"></p>
<p>密码:<input type="password" name="password"></p>
<p>昵称:<input type="text" name="nickname"></p>
<p>头像:<input id="headImg" type="file">
<input type="button" id="upload" value="上传文件">
</p>
<%--进度条--%>
<div class="progress">
<div></div>
</div>
<p><img id="head" alt="未选择图片"></p>
<input id="filetypeInput" type="hidden" name="filetype">
<input id="photoInput" type="hidden" name="photo">
<p><input type="submit" value="注册"></p>
</form>
</body>
</html>
二、页面代码
展现一个玩家列表
<html>
<head>
<title>Title</title>
<style>
#playerTable {
width: 50%;
border: 3px solid cadetblue;
margin: 0px auto;
text-align: center;
}
#playerTable th, td {
border: 1px solid gray;
}
#playerTable img {
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<table id="playerTable">
<tr>
<th>id</th>
<th>用户名</th>
<th>密码</th>
<th>昵称</th>
<th>头像</th>
</tr>
<tr>
<td>1</td>
<td>张三</td>
<td>123456</td>
<td>阿三</td>
<td>无</td>
</tr>
</table>
</body>
</html>
效果:
三、获取列表接口
1. Mapper层新增
接口:
/**
* 获取所有玩家
* @return
*/
List<Player> findAllPlayers();
映射文件:
<!--List<Player> findAllPlayers();-->
<select id="findAllPlayers" resultType="player">
select * from player
</select>
2. Service层新增
接口:
List<Player> findAllPlayers();
实现类:
@Override
public List<Player> findAllPlayers() {
return playerMapper.findAllPlayers();
}
3. Controller层新增
@RequestMapping("findAllPlayer.do")
@ResponseBody
public List<Player> findAllPlayer() {
List<Player> allPlayers = playerService.findAllPlayers();
System.out.println(allPlayers);
return allPlayers;
}
4. 页面中ajax请求数据
<script src="js/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$.ajax({
url: "findAllPlayer.do",
success: function (players) {
$.each(players, function (i, e) {
$("#playerTable").append(
"<tr>" +
"<td>" + e.id + "</td>" +
"<td>" + e.name + "</td>" +
"<td>" + e.password + "</td>" +
"<td>" + e.nickname + "</td>" +
"<td><img src='" + e.photo + "'></td>" +
"</tr>"
)
}
)
}
})
})
</script>
效果:
四、下载功能
1. 下载接口
下载需要设置响应头,Controller层新增接口:
@RequestMapping("download.do")
public void download(String photo, String filetype, HttpServletResponse response) throws IOException {
// 设置响应头
// 告诉浏览器要将数据保存到磁盘上,不在浏览器上直接解析
response.setHeader("Content-Disposition", "attachment;filename="+photo);
// 告诉浏览下载的文件类型
response.setContentType(filetype);
// 获取一个文件的输入流
InputStream inputStream = new URL(photo).openStream();
// 获取一个指向浏览器的输出流
ServletOutputStream outputStream = response.getOutputStream();
// 向浏览器响应文件即可
IOUtils.copy(inputStream, outputStream);
}
2. 页面修改
使用a标签的href属性调用接口进行下载
<html>
<head>
<title>Title</title>
<style>
#playerTable {
width: 50%;
border: 3px solid cadetblue;
margin: 0px auto;
text-align: center;
}
#playerTable th, td {
border: 1px solid gray;
}
#playerTable img {
width: 100px;
height: 100px;
}
</style>
<script src="js/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$.ajax({
url: "findAllPlayer.do",
success: function (players) {
$.each(players, function (i, e) {
$("#playerTable").append(
"<tr>" +
"<td>" + e.id + "</td>" +
"<td>" + e.name + "</td>" +
"<td>" + e.password + "</td>" +
"<td>" + e.nickname + "</td>" +
"<td><img src='" + e.photo + "'></td>" +
"<td><a href='download.do?photo=" + e.photo + "&filetype=" + e.filetype + "'>下载</a></td>" +
"</tr>"
)
}
)
}
})
})
</script>
</head>
<body>
<table id="playerTable">
<tr>
<th>id</th>
<th>用户名</th>
<th>密码</th>
<th>昵称</th>
<th>头像</th>
<th>下载</th>
</tr>
</table>
</body>
</html>
测试结果: