admin管理员组

文章数量:1033254

SpringBoot实现文件上传下载功能

SpringBoot实现文件上传下载功能

配置和前端页面

  • maven配置文件
代码语言:javascript代码运行次数:0运行复制
xml 代码解读复制代码    <dependencies>
        <!--  web模块      -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--  thymeleaf 模板引擎      -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>
  • 前端页面
代码语言:javascript代码运行次数:0运行复制
html 代码解读复制代码<!DOCTYPE html>
<html lang="en" xmlns:th=";>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src=".5.0/jquery.js"></script>
</head>
<body>
<h3>文件上传</h3>
<!--文件上传要求form表单的请求方式必须为post,并且添加属性enctype="multipart/form-data"-->
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" >
    <br>
    <input type="submit" value="上传" >
</form>

[[${filename}]]

<br>
<!--渲染上传的图片-->
<img th:src="@{${filename}}" alt="图片" id="imgss">
<h3>文件下载</h3>
<form action="/download" method="get">
    <input type="hidden" name="imageName" id="imageName" th:value="${filename}"/>
    <input type = "submit"  value="点击图片下载" >
</form>
</body>
</html>
  • webconfig配置
代码语言:javascript代码运行次数:0运行复制
java 代码解读复制代码@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        
        //  用于前端匹配路径 /AAA-uploaded/** 的时候 可以直接定位到D://AAA-uploaded/图片存储的地址
        //  用于前端页面渲染图片
        registry.addResourceHandler("/AAA-uploaded/**").
                addResourceLocations("file:/" + "D://AAA-uploaded/");
    }
}
  • yaml配置文件
代码语言:javascript代码运行次数:0运行复制
yaml 代码解读复制代码server:
  port: 8080

my-config:
  file-path: D:\

文件上传功能

MultipartFile接收前端传来的文件

代码语言:javascript代码运行次数:0运行复制
java 代码解读复制代码@Value("${my-config.file-path}")
    private String myFilePath;

    @RequestMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model) {
        try {
            //  避免图片名字重复 采用时间戳+图片名
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            //  获取图片存放路径
            String destFileName = myFilePath + "AAA-uploaded" + File.separator + fileName;
            File destFile = new File(destFileName);
            //  判断上一级目录是否存在 不存在则创建
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //  移动文件到指定目录下
            file.transferTo(destFile);
            //  存放到页面用于回显测试
            model.addAttribute("filename", "AAA-uploaded/" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        }
        return "index";
    }

文件下载功能

ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文

代码语言:javascript代码运行次数:0运行复制
java 代码解读复制代码@Value("${my-config.file-path}")
    private String myFilePath;
@ResponseBody
    @RequestMapping("/download")
    public ResponseEntity<byte[]> testResponseEntity(@RequestParam(value = "imageName", required = false) String 	filename) throws IOException {
        //  获取图片名称返回给页面用于下载
        String name = filename.split("/")[1];
        File newfile = new File("D:/AAA-uploaded" + File.separator + name);
        if (!newfile.exists()) {
            throw new IOException(name + "文件不存在");
        }
        //  创建输入流
        InputStream is = new FileInputStream(newfile);
        //  创建字节数组
        byte[] bytes = new byte[is.available()];
        //  将流读到字节数组中
        is.read(bytes);
        //  创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        //  设置要下载方式以及下载文件的名字
        headers.add("Content-Disposition", "attachment;filename="+ name);
        //  设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        //  创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
        //  关闭输入流
        is.close();
        return responseEntity;
    }

SpringBoot实现文件上传下载功能

SpringBoot实现文件上传下载功能

配置和前端页面

  • maven配置文件
代码语言:javascript代码运行次数:0运行复制
xml 代码解读复制代码    <dependencies>
        <!--  web模块      -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--  thymeleaf 模板引擎      -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
    </dependencies>
  • 前端页面
代码语言:javascript代码运行次数:0运行复制
html 代码解读复制代码<!DOCTYPE html>
<html lang="en" xmlns:th=";>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src=".5.0/jquery.js"></script>
</head>
<body>
<h3>文件上传</h3>
<!--文件上传要求form表单的请求方式必须为post,并且添加属性enctype="multipart/form-data"-->
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" >
    <br>
    <input type="submit" value="上传" >
</form>

[[${filename}]]

<br>
<!--渲染上传的图片-->
<img th:src="@{${filename}}" alt="图片" id="imgss">
<h3>文件下载</h3>
<form action="/download" method="get">
    <input type="hidden" name="imageName" id="imageName" th:value="${filename}"/>
    <input type = "submit"  value="点击图片下载" >
</form>
</body>
</html>
  • webconfig配置
代码语言:javascript代码运行次数:0运行复制
java 代码解读复制代码@Configuration
public class MyWebAppConfigurer implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        
        //  用于前端匹配路径 /AAA-uploaded/** 的时候 可以直接定位到D://AAA-uploaded/图片存储的地址
        //  用于前端页面渲染图片
        registry.addResourceHandler("/AAA-uploaded/**").
                addResourceLocations("file:/" + "D://AAA-uploaded/");
    }
}
  • yaml配置文件
代码语言:javascript代码运行次数:0运行复制
yaml 代码解读复制代码server:
  port: 8080

my-config:
  file-path: D:\

文件上传功能

MultipartFile接收前端传来的文件

代码语言:javascript代码运行次数:0运行复制
java 代码解读复制代码@Value("${my-config.file-path}")
    private String myFilePath;

    @RequestMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file, Model model) {
        try {
            //  避免图片名字重复 采用时间戳+图片名
            String fileName = System.currentTimeMillis() + file.getOriginalFilename();
            //  获取图片存放路径
            String destFileName = myFilePath + "AAA-uploaded" + File.separator + fileName;
            File destFile = new File(destFileName);
            //  判断上一级目录是否存在 不存在则创建
            if (!destFile.getParentFile().exists()) {
                destFile.getParentFile().mkdirs();
            }
            //  移动文件到指定目录下
            file.transferTo(destFile);
            //  存放到页面用于回显测试
            model.addAttribute("filename", "AAA-uploaded/" + fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        }
        return "index";
    }

文件下载功能

ResponseEntity用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览器的响应报文

代码语言:javascript代码运行次数:0运行复制
java 代码解读复制代码@Value("${my-config.file-path}")
    private String myFilePath;
@ResponseBody
    @RequestMapping("/download")
    public ResponseEntity<byte[]> testResponseEntity(@RequestParam(value = "imageName", required = false) String 	filename) throws IOException {
        //  获取图片名称返回给页面用于下载
        String name = filename.split("/")[1];
        File newfile = new File("D:/AAA-uploaded" + File.separator + name);
        if (!newfile.exists()) {
            throw new IOException(name + "文件不存在");
        }
        //  创建输入流
        InputStream is = new FileInputStream(newfile);
        //  创建字节数组
        byte[] bytes = new byte[is.available()];
        //  将流读到字节数组中
        is.read(bytes);
        //  创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        //  设置要下载方式以及下载文件的名字
        headers.add("Content-Disposition", "attachment;filename="+ name);
        //  设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        //  创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
        //  关闭输入流
        is.close();
        return responseEntity;
    }

本文标签: SpringBoot实现文件上传下载功能