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

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

1.导入依赖

        
        <dependency>
            <groupId>io.miniogroupId>
            <artifactId>minioartifactId>
            <version>3.0.10version>
        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 "下载失败";
        }
    }

}

你可能感兴趣的:(中间件,项目,java,minio)