Spring Boot 实现文件上传、下载功能

请添加图片描述

👨🏻‍💻 热爱摄影的程序员
👨🏻‍🎨 喜欢编码的设计师
🧕🏻 擅长设计的剪辑师
🧑🏻‍🏫 一位高冷无情的全栈工程师
欢迎分享 / 收藏 / 赞 / 在看!

Spring Boot 中实现图片上传和下载功能主要涉及到 Spring MVC 的 MultipartFile 类以及文件读写操作。

  1. 引入依赖
<dependency>  
    <groupId>org.springframework.boot</groupId>  
    <artifactId>spring-boot-starter-web</artifactId>  
</dependency>

<!-- lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.24</version>
</dependency>
  1. 编写配置
spring:
  servlet:
    multipart:
      max-file-size: 10MB # 单个文件最大大小
      max-request-size: 10MB # 请求最大大小
  1. 编写配置类
/**
 * 资源配置
 */
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {

    private final static RESOURCE_PREFIX = "/profile";
    
    private final static PROFILE = "/Users/hayden/Downloads";

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        // 本地文件上传路径
        registry.addResourceHandler(RESOURCE_PREFIX + "/**")
                .addResourceLocations("file:" + PROFILE + "/");
    }
}
  1. 编写 Controller
@Slf4j
@RestController
public class FileController {

    private final static RESOURCE_PREFIX = "/profile";
    
    private final static PROFILE = "/Users/hayden/Downloads";

    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.fail("上传文件不能为空");
        }
        String uploadDir = PROFILE + "/";
        String extension = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf("."));
        String fileName = System.currentTimeMillis() + extension;
        File dest = new File(uploadDir + fileName);

        String url = null;
        HashMap<String, String> map = new HashMap<>();
        try {
            file.transferTo(dest);
            url = serverConfig.getUrl() + RESOURCE_PREFIX + "/" + fileName;
            map.put("name", fileName);
            map.put("url", url);
        } catch (IOException e) {
            log.error("上传文件失败", e);
            return R.fail("上传文件失败", e.getMessage());
        }
        log.info("上传文件成功,文件:" + map);
        return R.ok(map);
    }
    
    @GetMapping("/download")
    public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
        if (fileName != null) {
            File file = new File(PROFILE + "/" + fileName);
            if (file.exists()) {
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int i = bis.read(buffer);
                    while (i != -1) {
                        os.write(buffer, 0, i);
                        i = bis.read(buffer);
                    }
                    log.info("下载文件成功,文件:" + fileName);
                } catch (Exception e) {
                    log.error("下载文件失败", e);
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }
}
  • 7
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

编程洪同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值