当然可以!使用MinIO客户端(MinIO Java SDK)来连接到阿里云OSS,并实现文件的上传和下载功能。以下是详细的步骤和示例代码。

1. 添加依赖

首先,在你的Spring Boot项目的pom.xml文件中添加MinIO的依赖:

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

2. 配置阿里云OSS

你需要在Spring Boot的配置文件(application.ymlapplication.properties)中添加阿里云OSS的相关配置信息:

minio:
  endpoint: "https://oss-cn-hangzhou.aliyuncs.com" # 阿里云OSS的Endpoint
  accessKey: "your-access-key" # 阿里云OSS的Access Key
  secretKey: "your-secret-key" # 阿里云OSS的Secret Key
  bucketName: "your-bucket-name" # 桶名称

3. 创建MinIO配置类

创建一个配置类来初始化MinIO客户端:

import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class MinioConfig {

    @Value("${minio.endpoint}")
    private String endpoint;

    @Value("${minio.accessKey}")
    private String accessKey;

    @Value("${minio.secretKey}")
    private String secretKey;

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }
}

4. 创建文件上传和下载服务

创建一个服务类来实现文件的上传和下载功能:

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class FileService {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 文件URL
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws MinioException
     */
    public String uploadFile(MultipartFile file) throws IOException, NoSuchAlgorithmException, InvalidKeyException, MinioException {
        try {
            // 检查桶是否存在,不存在则创建
            boolean isExist = minioClient.bucketExists(bucketName);
            if (!isExist) {
                minioClient.makeBucket(bucketName);
            }

            // 获取文件流
            InputStream inputStream = file.getInputStream();

            // 上传文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(bucketName)
                            .object(file.getOriginalFilename())
                            .stream(inputStream, file.getSize(), -1)
                            .contentType(file.getContentType())
                            .build()
            );

            // 构建文件访问URL
            String fileUrl = minioClient.getPresignedObjectUrl(
                    io.minio.GetPresignedObjectUrlArgs.builder()
                            .bucket(bucketName)
                            .object(file.getOriginalFilename())
                            .method(io.minio.http.Method.GET)
                            .expiry(7, java.util.concurrent.TimeUnit.DAYS)
                            .build()
            );

            return fileUrl;
        } catch (Exception e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }

    /**
     * 下载文件
     *
     * @param fileName 文件名
     * @return 文件流
     * @throws IOException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws MinioException
     */
    public InputStream downloadFile(String fileName) throws IOException, NoSuchAlgorithmException, InvalidKeyException, MinioException {
        try {
            return minioClient.getObject(
                    io.minio.GetObjectArgs.builder()
                            .bucket(bucketName)
                            .object(fileName)
                            .build()
            );
        } catch (Exception e) {
            throw new RuntimeException("文件下载失败", e);
        }
    }
}

5. 使用文件上传和下载功能

你可以在控制器中调用这些服务方法来实现文件的上传和下载:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

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

    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            String fileUrl = fileService.uploadFile(file);
            return ResponseEntity.ok(fileUrl);
        } catch (Exception e) {
            return ResponseEntity.status(500).body("文件上传失败");
        }
    }

    @GetMapping("/download/{fileName}")
    public ResponseEntity<InputStream> downloadFile(@PathVariable String fileName) {
        try {
            InputStream fileStream = fileService.downloadFile(fileName);
            return ResponseEntity.ok().body(fileStream);
        } catch (Exception e) {
            return ResponseEntity.status(500).body(null);
        }
    }
}

总结

以上代码展示了如何使用MinIO客户端连接到阿里云OSS,并实现文件的上传和下载功能。你可以根据实际需求调整配置和代码逻辑。希望这对你有所帮助!

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐