14-SpringBoot 文件上传与下载

在这里插入图片描述

1.配置文件

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.limi</groupId>
    <artifactId>springboot-test2</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot-test2</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>

            <!-- 下面插件作用是工程打包时,不将spring-boot-configuration-processor打进包内,让其只在编码的时候有用 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-configuration-processor</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

application.properties

server.port=8080
#单个文件大小最大限制
spring.servlet.multipart.max-file-size=100MB
#一次请求中全部文件大小之和的最大限制
spring.servlet.multipart.max-request-size=1000MB

2.java代码

SpringbootTest2Application

package com.limi.springboottest2;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class SpringbootTest2Application {
;
    public static void main(String[] args) {

        //1、返回我们IOC容器
        ConfigurableApplicationContext run = SpringApplication.run(SpringbootTest2Application.class, args);
    }

}

HelloController

package com.limi.springboottest2.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Controller
public class HelloController {

    @GetMapping("/down")
    public String down(){
        return "/view/down.html";
    }

    @GetMapping("/up")
    public String up(){
        return "/view/up.html";
    }

    //下载文件
    @GetMapping("/testDown")
    public ResponseEntity<byte[]> testResponseEntity(String filePath) throws IOException {

        String suffix = filePath.substring(filePath.lastIndexOf('.')); //获取文件后缀
        String fileName =  UUID.randomUUID().toString()+suffix;  //文件名 = uuid+文件后缀
        //创建输入流
        InputStream is = new FileInputStream(filePath);
        //创建字节数组
        byte[] bytes = new byte[is.available()];
        //将流读到字节数组中
        is.read(bytes);
        //创建HttpHeaders对象设置响应头信息
        MultiValueMap<String, String> headers = new HttpHeaders();
        //设置要下载方式以及下载文件的名字, 只有filename="xxx"可以自定义, "Content-Disposition", "attachment;"是固定写法
        headers.add("Content-Disposition", "attachment;filename="+fileName);
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<byte[]>(bytes, headers, statusCode);
        //关闭输入流
        is.close();
        return responseEntity;
    }


    @ResponseBody
    @PostMapping("/testUp")
    public String upload(@RequestParam("email") String email,
                         @RequestParam("username") String username,
                         @RequestPart("headerImg") MultipartFile headerImg,
                         @RequestPart("photos") MultipartFile[] photos) throws IOException {

        System.out.println(email+"\n"+username);
        if(!headerImg.isEmpty()){
            //获取上传的文件的文件名
            String fileName = headerImg.getOriginalFilename();
            //处理文件重名问题
            String suffix = fileName.substring(fileName.lastIndexOf("."));
            fileName = UUID.randomUUID().toString() + suffix;
            //图片存储文件夹路径, 请替换成你电脑下存在的文件夹路径
            String dir = "E:\\Office文档\\tu\\file\\upload";
            String finalPath = dir + File.separator + fileName;
            //实现上传功能
            headerImg.transferTo(new File(finalPath));
        }

        if(photos.length > 0){
            for (MultipartFile photo : photos) {
                if(!photo.isEmpty()){
                    String fileName = photo.getOriginalFilename();
                    String suffix = fileName.substring(fileName.lastIndexOf("."));
                    fileName = UUID.randomUUID().toString() + suffix;
                    //图片存储文件夹路径, 请替换成你电脑下存在的文件夹路径
                    String dir = "E:\\Office文档\\tu\\file\\upload";
                    String finalPath = dir + File.separator + fileName;
                    //实现上传功能
                    photo.transferTo(new File(finalPath));
                }
            }
        }
        return "success!";
    }

}

3.前端代码

下载页面down.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>hello world!</h1>

<form action="/testDown" method="get">
    文件路径:<input type="text" name="filePath"><br>
    <input type="submit" value="下载">
</form>

</body>
</html>

上传页面up.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>hello world!</h1>

<form action="/testUp" method="post" enctype="multipart/form-data">
    单个图片:<input type="file" name="headerImg"><br>
    用户名:<input type="text" name="username"><br>
    邮箱:<input type="email" name="email"><br>
    多个图片:<input type="file" name="photos" multiple><br>
    <input type="submit" value="上传">
</form>

</body>
</html>


4.运行测试

1.测试下载

在这里插入图片描述

在这里插入图片描述
下载成功
在这里插入图片描述

2.测试上传

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
上传成功
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值