SpringBoot实现文件上传和下载

1.代码实现

springboot自己集成了MultipartFile,可以在配置文件中设置上传文件大小的限制

@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${upload.path}")
    public String uploadPath;

    @PostMapping("/upload")
    public boolean upload(MultipartFile file, String fileName){
        if(file==null) return false;
        if(fileName==null) fileName = file.getOriginalFilename();
        try {
            file.transferTo(new File(uploadPath+fileName));
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            return true;
        }
    }

    @GetMapping("/download")
    public void download(String path, HttpServletResponse response) throws Exception {
        String fileName = null;
        FileInputStream fis = null;
        File file = new File(uploadPath+path);
        if(path.contains("/"))fileName = path.substring(path.lastIndexOf("/"),path.length());
        else fileName = path;//如果文件在根路径
        if(!file.exists()) {errorPath("系统找不到指定的路径",response);return;}
        if(file.isDirectory()) {errorPath("文件夹不可下载",response);return;}
        //附件形式下载
        response.setHeader("content-disposition","attachment;fileName="+ URLEncoder.encode(fileName,"UTF-8"));
        response.setContentType("form/data;charset=utf-8");
        FileCopyUtils.copy(fis,response.getOutputStream());
    }
    
    public void errorPath(String message,HttpServletResponse response) throws IOException {
        response.setContentType("text/plain;charset=utf-8");
        response.getWriter().write(message);
    }
}

配置文件

server.servlet.context-path=/webfile
server.port=8888
upload.path=D:/

2.测试

1)文件上传采用postman测试
在这里插入图片描述
2)文件的下载可以直接在浏览器测试接口
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值