SSM实现文件/图片上传与下载
添加依赖
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<!-- 文件上传 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
首先在spring-mvc.xml中添加
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设定默认编码 -->
<property name="defaultEncoding" value="UTF-8"></property>
<!-- 设定文件上传的最大值为5MB,5*1024*1024 -->
<property name="maxUploadSize" value="5242880"></property>
</bean>
实现上传的Controller
注意from表单的enctype应设置为"multipart/form-data"
指定传输数据为二进制类型,比如图片、mp3、文件。
@RequestMapping("/addhouse")
public String addHouse(HouseList houseList, HttpServletResponse response, MultipartFile file, ModelMap map)
throws IOException {
String uuid= UUID.randomUUID().toString();
houseList.setId(uuid.replace("-",""));
/**
* 上传图片
*/
//图片上传成功后,将图片的地址写到数据库
String filePath = "E:\\upload";//保存图片的路径
//获取原始图片的拓展名
String originalFilename = file.getOriginalFilename();
//新的文件名字
String newFileName = UUID.randomUUID().toString().replace("-","")+originalFilename;
//封装上传文件位置的全路径
File targetFile = new File(filePath,newFileName);
//把本地文件上传到封装上传文件位置的全路径
file.transferTo(targetFile);
houseList.setImage(newFileName);
houseListSevice.insert(houseList);
return "redirect:/houselist";
}
图片展示
@RequestMapping("/show")
public String show(Model model,@RequestParam("id") String id){
HouseList houseList=houseListSevice.show(id);
if (houseList!=null){
model.addAttribute("list",houseList);
return "admin/show";
}
else {
return "admin/error";
}
}
jsp页面代码`
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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 rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css"/>
<title>详情</title>
</head>
<body>
<table class="table table-bordered table-hover">
<tr>
<th><c:if test="${list.image !=null }">
<img id="images" alt="" src="/image/${list.image }">//图片展示
</c:if> </th>
<th> <a id="a" href="${pageContext.request.contextPath}/fileDownload.do?fileName=${list.image}" >
</a>
</th>
</tr>
</table>
</body>
<script >
var filename="${list.image}"
var file=filename.slice(32)//截取字符串去掉UUID
document.getElementById("a").innerText=file//设置到<a>标签
</script>
</html>
实现文件下载的Controller
@RequestMapping(value = "fileDownload.do")
public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, @RequestParam(value = "fileName") String fileName)
throws Exception {
String fName = fileName.substring(fileName.lastIndexOf("_") + 1); // 从 uuid_name.jpg中截取文件名
//根据文件的绝对路径,获取文件
File file = new File("E:/upload/"+fName);
//设置请求头
HttpHeaders headers = new HttpHeaders();
fileName = new String(fileName.getBytes("utf-8"), "iso8859-1");
headers.add("Content-Disposition", "attachment;filename=" + fileName);
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, statusCode);
return response;
}
<下载的链接在上面的jsp代码里 id=“a”>
特别注意的是需要将上传路径配置到tomcat中
1.修改idea的tomcat配置
选择本地上传的文件夹 更改路径为image
2.修改server.xml
打开 Tomcat conf 文件夹下的 server.xml 文件,在 Host 节点下添加如下配置:
docBase 为文件保存路径, path 为文件访问路径。