minio附件功能接入核心代码总结

package service;
@Slf4j
public class MinIOFileUploader implements FileUploader {

  /** bucketName */
  private String bucketName ;

  /** accessKey */
  private String accessKey ;

  /** secretKey */
  private String secretKey;

  /** endpoint */
  private String endpoint ;

  /** download ip */
  private String host ;

  /** S3Client*/
   AmazonS3 s3;

  /**
   * 构造方法
   *
   * @param bucketName
   * @param accessKey
   * @param secretKey
   * @param endpoint
   * @param host
   */
  public MinIOFileUploader(
          String bucketName, String accessKey,String secretKey, String endpoint, String host) {
    this.bucketName = bucketName;
    this.accessKey = accessKey;
    this.secretKey = secretKey;
    this.endpoint = endpoint;
    this.host = host;
  }

  /**
   * 附件上传实现类
   * @author 拿铁
   * @date 2021/09/13
   * @return  String
   * */
  @Override
  public String upload(MultipartFile file)
          throws FileExtensionNotFoundException, IOException, InterruptedException,
          UriFormatUnmatchedException {
    String fileType = file.getOriginalFilename();
    fileType = !ObjectUtils.isEmpty(fileType) && fileType.contains(".") ?
            fileType.split("\\.")[1] : fileType;

    String tempFileName =  FileUtils.generateRandomFileName() + "." +fileType;
    String contentType = file.getContentType();
    long fileSize = file.getSize();
    ObjectMetadata objectMetadata = new ObjectMetadata();
    objectMetadata.setContentType(contentType);
    objectMetadata.setContentLength(fileSize);
    initS3();
    //存在则打印桶
    if (!s3.doesBucketExistV2(bucketName)) {
      //不存在则创建桶
      s3.createBucket(bucketName);
    }
    s3.putObject(bucketName, tempFileName, file.getInputStream(), objectMetadata);
    return host + tempFileName;
  }

  /**
   * 附件下载地址接口,直接返回文件(实时调接口获取文件)
   * @author 拿铁
   * @date 2021/09/15
   * */
  @Override
  public void download(String key, HttpServletResponse response,String fileName) {
    S3ObjectInputStream s3input = null;
    ServletOutputStream outputStream = null;
    try {
      initS3();
      S3Object S3Result = s3.getObject(bucketName, key);
      s3input = S3Result.getObjectContent();
      response.addHeader("Content-Disposition", "attachment; filename=" +
              URLEncoder.encode(fileName, "UTF-8"));
      outputStream = response.getOutputStream();
      byte[] readBuf = new byte[1024];
      int readLen = 0;
      while ((readLen = s3input.read(readBuf)) > 0) {
        outputStream.write(readBuf, 0, readLen);
      }
    } catch (AmazonServiceException e) {
      throw new RuntimeException();
    } catch (FileNotFoundException e) {
      throw new RuntimeException();
    } catch (IOException e) {
      throw new RuntimeException();
    }finally {
      try {
        s3input.close();
        outputStream.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

  /**
   * 获取附件下载地址url
   * @author 拿铁
   * @date 2021/09/13
   * @return url
   * */
	public String generatePresignedUrl(String tempFileName) {
 		URL url ;    
 		try {
	      Date expiration = new Date();
	      long expTimeMillis = Instant.now().toEpochMilli();
	      expTimeMillis += 1000 * 60 * 60;
	      expiration.setTime(expTimeMillis);
	      GeneratePresignedUrlRequest generatePresignedUrlRequest =
	              new GeneratePresignedUrlRequest(bucketName, tempFileName)
	                      .withMethod(HttpMethod.GET)
	                      .withExpiration(expiration);
	
	      url = s3.generatePresignedUrl(generatePresignedUrlRequest);
	      System.out.println(url);
	      } catch (AmazonServiceException e) {
		      System.out.println(e.getErrorMessage());
		      throw new RuntimeException();
	      }
      return url.toString();
  }

  /**
   * 初始化S3Client
   * @author 拿铁
   * @date 2021/09/13
   * */
	public void initS3() {
	    ClientConfiguration config = new ClientConfiguration();
		AwsClientBuilder.EndpointConfiguration endpointConfig =
		new AwsClientBuilder.EndpointConfiguration(endpoint, "us-east-1");
		AWSCredentials awsCredentials = new BasicAWSCredentials(accessKey, secretKey);
	    AWSCredentialsProvider awsCredentialsProvider = new AWSStaticCredentialsProvider(awsCredentials);    
	    s3  = AmazonS3ClientBuilder.standard()
	            .withEndpointConfiguration(endpointConfig)
	            .withClientConfiguration(config)
	            .withCredentials(awsCredentialsProvider)
	            .disableChunkedEncoding()
	            .withPathStyleAccessEnabled(true)
	            .build();
	  }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,你的问题是springboot如何接入minio,这个问题涉及到在springboot中引入minio依赖、配置连接信息以及使用minio进行文件上传等方面。具体步骤可以参考以下内容: 1. 在pom.xml中引入minio依赖: ```xml <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>7.1.0</version> </dependency> ``` 2. 在application.yml或application.properties中配置minio连接信息: ```yaml spring: minio: endpoint: http://minio.example.com accessKey: accesskey secretKey: secretkey ``` 3. 创建MinioTemplate类用于封装MinioClient操作: ```java @Configuration public class MinioConfig { @Value("${spring.minio.endpoint}") private String endpoint; @Value("${spring.minio.accessKey}") private String accessKey; @Value("${spring.minio.secretKey}") private String secretKey; @Value("${spring.minio.bucketName}") private String bucketName; @Bean public MinioClient minioClient() throws Exception { return MinioClient.builder() .endpoint(endpoint) .credentials(accessKey, secretKey) .build(); } @Bean public MinioTemplate minioTemplate(MinioClient minioClient) { return new MinioTemplate(minioClient, bucketName); } } public class MinioTemplate { private final MinioClient minioClient; private final String bucketName; public MinioTemplate(MinioClient minioClient, String bucketName) { this.minioClient = minioClient; this.bucketName = bucketName; } public void upload(String objectName, InputStream inputStream, long size, String contentType) throws Exception { PutObjectArgs args = PutObjectArgs.builder() .bucket(bucketName) .object(objectName) .stream(inputStream, size, -1) .contentType(contentType) .build(); minioClient.putObject(args); } public void remove(String objectName) throws Exception { RemoveObjectArgs args = RemoveObjectArgs.builder() .bucket(bucketName) .object(objectName) .build(); minioClient.removeObject(args); } public String getObjectUrl(String objectName) { return minioClient.getObjectUrl(bucketName, objectName); } } ``` 4. 在Controller中使用MinioTemplate上传文件: ```java @RestController public class FileController { @Autowired private MinioTemplate minioTemplate; @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) throws Exception { String objectName = file.getOriginalFilename(); InputStream inputStream = file.getInputStream(); long size = file.getSize(); String contentType = file.getContentType(); minioTemplate.upload(objectName, inputStream, size, contentType); String objectUrl = minioTemplate.getObjectUrl(objectName); return objectUrl; } } ``` 以上就是springboot接入minio的大致步骤,具体细节还需要根据实际情况进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值