文件上传(图片),并显示--------使用springboot的thymeleaf模板引擎
- application.properties配置thymeleaf
#关闭缓存
spring.thymeleaf.cache=false
#去掉严格校验,要添加依赖
spring.thymeleaf.mode=LEGANCYHTML5
#前缀
spring.thymeleaf.suffix=.html
spring.thymeleaf.prefix=classpath:/templates/
#静态资源所在路径,这个非常重要
spring.resources.static-locations=classpath:/templates/,classpath:/static/
//去掉严格校验的依赖
<dependency>
<groupId>net.sourceforge.nekohtml</groupId>
<artifactId>nekohtml</artifactId>
<version>1.9.22</version>
</dependency>
//获取后缀的工具类
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
- 文件上传
//表单的方法要post ,而且必须加上enctype="multipart/form-data"
<h3>上传文件</h3>
<form th:action="@{/file/upload}" method="post" enctype="multipart/form-data">
<input type="file" name="aaa">
<input type="submit" value="上传文件">
</form>
/**
* 上传文件的处理
*/
@PostMapping("upload")
public String uploas(MultipartFile aaa,HttpSession session) throws IOException {
//获取用户上传的id
User user = (User) session.getAttribute("user");
//获取文件原始名称
String oldFileName = aaa.getOriginalFilename();
//获取文件的后缀
String extension = "."+FilenameUtils.getExtension(aaa.getOriginalFilename());
//String extension = oldFileName.substring(oldFileName.lastIndexOf("."));
//生成新的文件名称
String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + UUID.randomUUID().toString().replace("-", "") + extension;
//文件大小
Long size = aaa.getSize();
//文件类型
String type = aaa.getContentType();
//处理根据日期生成目录 一定要加/static ,因为是上传到static 下的 ,不然获取不到
String realPath = ResourceUtils.getURL("classpath:").getPath() + "/static/files2";
String dateFormat = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String dateDirPath=realPath + "/" + dateFormat;
File dateDir = new File(dateDirPath);
if (!dateDir.exists()) {
dateDir.mkdirs();
}
//处理文件上传
System.out.println("上传的路径:"+dateDir);
aaa.transferTo(new File(dateDir,newFileName));
//将文件信息放入数据库保存
UserFile userFile = new UserFile();
userFile.setOldFileName(oldFileName).setNewFileName(newFileName).setExt(extension).setSize(String.valueOf(size))
.setType(type).setPath("/files2/" + dateFormat).setUserId(user.getId());
//上传的路径:D:\Idea\Idea-project\alldemo\files\target\classes\static\files2\2020-08-12
userFileService.save(userFile);
return "redirect:/file/showAll";
}
可以说${pageContext.request.contextPath}等价于<%=request.getContextPath()%>!它们的意思就是取得当前项目名称(或者是–取出部署的应用程序名 )
//判断是否图片
//是否图片:解决方案 :当类型中含有image即说明当前类型一定是图片,写在service层
String isImg=userFile.getType().startsWith("image") ? "是" : "否";
<img th:if="${file.isImg}=='是'" style="width: 100px;height: 40px;" th:src="${#servletContext.contextPath}+${file.path}+'/'+${file.newFileName}" alt="">
- 注意
获取到项目的D:\Idea\Idea-project\alldemo\files\target\classes的目录
ResourceUtils.getURL("classpath:").getPath()
${#servletContext.contextPath}//必须配置thymeleaf的静态资源目录,配置了这个直接能拿到项目的static了
spring.resources.static-locations=classpath:/templates/,classpath:/static/
文件的下载----及在线打开
/**
* 文件下载
*/
@GetMapping("download")
public void download(String id, HttpServletResponse response) throws IOException {
//获取文件的信息
UserFile userFile = userFileService.findById(id);
//根据文件信息中的文件名字 和 文件存储路径获取文件输入流
String realpath = ResourceUtils.getURL("classpath:").getPath() + "/static" + userFile.getPath();
//获取文件输入流
FileInputStream is = new FileInputStream(new File(realpath, userFile.getNewFileName()));
//附件下载----把attachment改为inline或者删除设置响应头就变成在线打开了
response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(userFile.getOldFileName(),"UTF-8"));
//获取响应输出流
ServletOutputStream os = response.getOutputStream();
//文件拷贝
IOUtils.copy(is,os);
//关闭流
IOUtils.closeQuietly(is);
IOUtils.closeQuietly(os);
}