java 上传下载文件(minIO版)

在这里插入图片描述

首先需要安装minIO,公司有的话最好,没有那就自己本地安装一个。
推荐安装文章https://blog.youkuaiyun.com/qq_38974638/article/details/115678147

1.引入依赖

<dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>8.5.2</version>
</dependency>

因为我的JDK是17,版本大家自己斟酌哈,让我看看还有谁在用 8 🥺🥺🥺

2.配置文件

minio:
  endpoint: http://127.0.0.1:9000/minio/
  access-key: minioadmin
  secret-key: minioadmin
  bucketName: demo

前三个配置,如果本地安装默认应该是这个配置,最后一个是需要大家自己去minIO创建的哈,如果使用公司的需要问下配置的;

3.创建MinioConfig的配置文件

package com.wangyang.demo17.config;

import io.minio.MinioClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucketName;
    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }
}

该配置类,会读取第二步中的四个配置,在项目启动时,创建 MinioConfig 对象;后面我们只需
@Autowired 注入该 bean 对象即可正常使用;

4.上传下载

package com.wangyang.demo17.controller;

import com.wangyang.demo17.config.MinioConfig;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.UUID;


@RestController
@RequestMapping("/minio")
public class MinIOController {
  @Autowired
  private MinioClient minioClient;
  @Autowired
  private MinioConfig minioConfig;

  @PostMapping("/up")
  public String uploadFile(@RequestPart MultipartFile file) throws Exception {
    String fileType = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    String fileName = UUID.randomUUID().toString().replace("-", "") + fileType;
    minioClient.putObject(PutObjectArgs.builder()
        .bucket(minioConfig.getBucketName())
        .object(fileName)
        .stream(file.getInputStream(), file.getInputStream().available(), -1)
        .contentType(file.getContentType())
        .build());
    return fileName;
  }

  @PostMapping("/down")
  public void downLoad(@RequestParam("fileName") String fileName, HttpServletResponse response) {
    try (OutputStream outputStream = response.getOutputStream();
         InputStream inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(minioConfig.getBucketName()).object(fileName).build());) {
      // 获取文件对象
      byte buf[] = new byte[1024];
      int length = 0;
      response.reset();
      response.setHeader("Content-Disposition", "attachment;filename=" +
          URLEncoder.encode(fileName.substring(fileName.lastIndexOf("/") + 1), "UTF-8"));
      response.setContentType("application/octet-stream");
      response.setCharacterEncoding("UTF-8");
      // 输出文件
      while ((length = inputStream.read(buf)) > 0) {
        outputStream.write(buf, 0, length);
      }
    } catch (Throwable ex) {
      response.setHeader("Content-type", "text/html;charset=UTF-8");
      String data = "文件下载失败";
      try {
        OutputStream ps = response.getOutputStream();
        ps.write(data.getBytes("UTF-8"));
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
}

上传返回的文件名称是uuid加上文件后缀,防止重复上传,导致文件名称重复而上传失败,fileName可作为下载的参数直接使用,这里方便大家阅读就不分sevice层级了。

以上就是全部代码,均已验证可行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值