SpringBoot2.X实现文件上传与下载

本例子基于spring-boot-2.1.6.RELEASE开发
pom文件:

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <!--spring-boot-web-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
     </dependencies>

springboot对于文件上传的yml配置

spring:
  servlet:
    multipart:
      max-file-size: 2MB #上传一个文件最大值 默认是1MB
      max-request-size: 20MB #上传多个文件最大值  默认是10MB

直接上代码

import org.springframework.http.MediaType;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping(path = "/", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class FileController {
    final String path = "D:\\tmp\\";

    final String fileName = "D:\\tmp\\你好.txt";

    //文件上传
    @PostMapping(path = "/upload")
    public String upload(@RequestParam("file") MultipartFile file, HttpServletResponse response) {
     //获取原始文件名
        String originalFilename = file.getOriginalFilename();
        File localFile = new File(path + originalFilename);
        try {
         //直接将文件拷贝到指定位置
            file.transferTo(localFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (localFile.exists()) {
            return "ok";
        } else {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return "error";
        }
    }

    //批量文件上传
    @PostMapping(path = "/uploads")
    public String uploadFiles(@RequestParam("file") MultipartFile[] files, HttpServletResponse response) {
        boolean result = true;
        StringBuilder stringBuilder = new StringBuilder();
        for (MultipartFile file : files) {
         //获取原始文件名
            String originalFilename = file.getOriginalFilename();
            File localFile = new File(path + originalFilename);
            try {
             //直接将文件拷贝到指定位置
                file.transferTo(localFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            boolean exists = localFile.exists();
            if (!exists) {
                result = false;
                stringBuilder.append(file.getOriginalFilename()).append(" ");
            }
        }
        if (result) {
            return "ok";
        }
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return "upload fail, file name : " + stringBuilder.toString();
    }

    //文件下载
    @GetMapping("/download")
    public void downloadFile(HttpServletResponse response) {
        File file = new File(fileName);
        if (file.exists()) {
            try (FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fis)) {
                response.setContentType("application/force-download");
                //保证下载时文件名为指定文件名,避免中文文件名乱码
                response.addHeader("Content-Disposition", "attachment;fileName="
                        + URLEncoder.encode(file.getName(), "utf-8"));
                OutputStream os = response.getOutputStream();
                StreamUtils.copy(bis, os);
            } catch (Exception e) {
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                e.printStackTrace();
            }
        }
    }
}

测试上传单个文件
 

图片


测试上传多个文件
 

图片


下载文件测试直接使用浏览器请求接口URL即可

对于通过SpringCloudZuul映射后的文件上传请求,在文件上传时请求的url中需要加上/zuul前缀才能保证中文不乱码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值