springboot整合thymeleaf模板,上传文件及时回显和下载的功能。

1、第一步在配置文件中自定义文件上传路径,访问路径
springboot整合thymeleaf模板,上传文件及时回显和下载的功能。_第1张图片
第二步需要创建两个html页面,模板选用thymeleaf

<!--文件上传第一次跳转-->
   <!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form th:action="@{/upload}" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>
</body>
</html>

//回显的时候取值可能会出现红色下划线这是正常情况不用理会
在这里插入图片描述

<!--文件上传以后回显并且下载-->
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>上传文件</title>
</head>
<body>
<img th:src="@{${filePath}}" alt="">
<a th:href="@{/download/(filepath=${filePath},fileName=${fileName})}">下载</a>
</body>
</html>

第三步就是建一个控制层Controller类并且同时创建配置类Configration
2、下面直接上代码:
1) 控制层代码:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
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.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
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;

@Controller
public class FileController {

    private static final Logger LOGGER =
            LoggerFactory.getLogger(FileController.class);
    @Value("${uploadpath}")
    private String uploadpath;

    @GetMapping("/toUpload")
    public String toUpload(){
        return "index/upload";
    }

    @Value("${vpath}")
    public String vpath;

    @PostMapping("/upload")
    public String upload(MultipartFile file, HttpServletRequest request, ModelMap map){
        //获取上传的文件名
        String filename=file.getOriginalFilename();
        LOGGER.error("文件名:"+filename);
        //构建保存的位置,绝对路径+文件名
        File filel=new File(uploadpath,filename);
        //如果父目录不存在,则创建父目录
        if(!filel.getParentFile().exists()){
            filel.getParentFile().mkdirs();
        }
        try{
            file.transferTo(filel);
        } catch (IOException e) {
            //记录错误日志
            LOGGER.error("上传文件异常",e);
        }
        map.put("fileName",filename);
        map.put("filePath",vpath+filename);// uploadFile/a.jpg
        return "index/fileInfo";
    }
    //文件下载
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(
            String fileName
    ) throws IOException {
   /*     //获取文件真实路径
        String realPath = request.getServletContext().getRealPath(path);*/
        //创建文件对象
        File file=new File(uploadpath,fileName);
        //构建响应头
        HttpHeaders headers=new HttpHeaders();
        //设置以附件形式打开
        headers.setContentDispositionFormData("attachment",
                new String(fileName.getBytes("UTF-8"),
                        "iso-8859-1"));
        //设置文档类型为stream
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(
                FileCopyUtils.copyToByteArray(file),//文件字节数组
                headers,//头部信息
                HttpStatus.CREATED);//http状态码
    }
}

2)配置类代码:

 import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/*
 * 文件上传路径映射配置类
 * WebMvcConfigurer 用来配置springmvc中的一些配置信息
 * */
@Configuration//配置类注解
public class WebAppConfig implements WebMvcConfigurer {
 @Value("${uploadpath}")
 private String uploadpath;

 @Value("${vpath}")
 private String vpath;

 //添加资源映射
 /*
  * ResourceHandlers 相当于springmvc配置resource配置项
  * */
 @Override
 public void addResourceHandlers(ResourceHandlerRegistry registry) {
  registry.addResourceHandler(vpath + "**")//指定请求URL
          //"file:D:/upload"
          .addResourceLocations("file:" + uploadpath);//指定映射到的资源
 }

}

效果图:
springboot整合thymeleaf模板,上传文件及时回显和下载的功能。_第2张图片
在配置文件中还需要配置上传的大小(根据自己的需求配置)
springboot整合thymeleaf模板,上传文件及时回显和下载的功能。_第3张图片

你可能感兴趣的:(springboot,File)