SpringBoot 简单文件上传下载

SpringBoot 简单文件上传下载

配置文件路径

spring:
  servlet:
    multipart:
      max-file-size: 50MB
      max-request-size: 100MB
file:
  path: /Users/jisen/Desktop
  folder: /files/

文件上传核心代码

package com.demo.studynew;

import cn.hutool.core.io.IoUtil;
import org.springframework.beans.factory.annotation.Value;
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("file")
public class FileController {

    @Value("${file.path}")
    private String filePath;

    @Value("${file.folder}")
    private String fileFolder;

    @PostMapping("upload")
    public String upload(@RequestParam("file") MultipartFile file){
        String originalFilename = file.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf("."));
        File dest = new File(filePath +fileFolder+ System.currentTimeMillis() + "" + suffixName);
        try {
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
            return fileFolder + dest.getName();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

    @GetMapping(value = "download",produces = "application/octet-stream")
    public void download(String fileUrl, HttpServletResponse response) {
        String filename = null;
        try {
            filename = fileUrl.substring(fileUrl.lastIndexOf("/")+1);
        } catch (Exception e) {
            throw new RuntimeException("文件不存在");
        }

        if (!fileUrl.contains(fileFolder)) {
            throw new RuntimeException("文件不存在");
        }
        fileUrl = fileUrl.split(fileFolder)[1];
        File file = new File(filePath + fileFolder + fileUrl);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在");
        }
        InputStream is = null;
        OutputStream os = null;
        try {
            response.setHeader("content-Type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename,"utf-8"));
            os = response.getOutputStream();
            is = new FileInputStream(file);
            IoUtil.copy(is, os, 8192);
            os.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(os);
            IoUtil.close(is);
        }
    }
}

资源映射

package com.demo.studynew;

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;

@Configuration
public class  WebConfig implements WebMvcConfigurer {

    @Value("${file.path}")
    private String filePath;

    @Value("${file.folder}")
    private String fileFolder;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(fileFolder + "**").addResourceLocations("file:" + filePath + fileFolder);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值