SpringBoot整合minio文件系统实现文件上传并返回文件的可访问路径

本文档介绍了如何在SpringBoot项目中整合Minio文件服务器,用于实现文件的上传和下载功能。首先引入Minio的依赖,然后配置Minio的URL、访问Key和密钥。接着在Controller中创建上传接口,通过MinioClient将文件保存至Minio,并返回文件的预签名URL。同时提供了下载接口,允许用户按需下载存储在Minio上的文件。
摘要由CSDN通过智能技术生成

今天项目中甲方指定了一个以前没用过的文件服务器,捅咕半天,记录一下使用方法。

1.导入依赖

        <!--    springboot整合minio        -->
        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>3.0.10</version>
        </dependency>

2.配置文件

upload:
  url: http://ip:端口
  accessKey: 公钥
  secretKey: 密钥

3.controller


import com.google.api.client.util.IOUtils;
import com.ruoyi.system.domain.Result;
import io.minio.MinioClient;
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.InputStream;
import java.util.UUID;

/**
 * @author yhd
 * @createtime 2020/10/16 11:13
 * 文件上传到minio服务器的接口
 */
@RestController
@RequestMapping("file")
public class FileUpLoadController {

    @Value("${upload.url}")
    private  String url ;
    @Value("${upload.accessKey}")
    private  String accessKey ;
    @Value("${upload.secretKey}")
    private  String secretKey ;

    @PostMapping("upload")
    public Result<String> upload(@RequestParam("fileName") MultipartFile file ) throws Exception {

            MinioClient minioClient = new MinioClient(url, accessKey, secretKey);
            InputStream is= file.getInputStream(); //得到文件流
            String fileName = UUID.randomUUID().toString().replace("-","")+file.getOriginalFilename(); //文件名
            String contentType = file.getContentType();  //类型
            minioClient.putObject("file",fileName,is,contentType); //把文件放置Minio桶(文件夹)
            String url = minioClient.presignedGetObject("file", fileName);
            return Result.ok(url);

    }
    //下载minio服务的文件
    @GetMapping("download")
    public String download(HttpServletResponse response){
        try {
            MinioClient minioClient = new MinioClient(url, accessKey, secretKey);
            InputStream fileInputStream = minioClient.getObject("file", "test.jpg");
            response.setHeader("Content-Disposition", "attachment;filename=" + "test.jpg");
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            IOUtils.copy(fileInputStream,response.getOutputStream());
            return "下载完成";
        }catch (Exception e){
            return "下载失败";
        }
    }

}
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值