java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot minio文件上传

SpringBoot集成minio实现文件上传和删除功能

作者:我心向阳cd

这篇文章主要介绍了SpringBoot集成minio实现文件上传和删除功能,详细介绍每个功能的实现步骤和代码示例,具有一定的参考价值,感兴趣的可以了解一下

1.加入依赖

<!-- 对象存储 Minio -->
        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>${minio.version}</version>
        </dependency>

2.yml配置

minio:
  endpoint: http://ip:9000
  accessKey: accessKey
  secretKey: secretKey
  bucketName: bucketName

3.配置类

@Configuration
public class MinioConfig {
 
    @Autowired
    private MinioProperties minioProperties;
 
    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(minioProperties.getEndpoint())
                .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                .build();
    }
}

4.属性配置类

@ConfigurationProperties(prefix = "minio")
@Component
@Data
public class MinioProperties {
    private String endpoint;
    private String accessKey;
    private String secretKey;
    private String bucketName;
}

5.工具类:示例文件上传和删除

@Component
@Slf4j
public class MinioUtil {
 
    @Autowired
    private MinioProperties minioProperties;
 
    @Autowired
    private MinioClient minioClient;
 
    public String uploadFile(MultipartFile file, String bucketName) throws Exception {
        if (file == null || file.getSize() == 0) {
            log.error("==> 上传文件异常:文件大小为空 ...");
            throw new RuntimeException("请选择需要上传的文件");
        }
 
        String originalFileName = file.getOriginalFilename();
        String contentType = file.getContentType();
 
        String key = UUID.randomUUID().toString().replace("-", "");
        String suffix = originalFileName.substring(originalFileName.lastIndexOf("."));
        String objectName = String.format("%s%s", key, suffix);
        log.info("==> 开始上传文件至 Minio, ObjectName: {}", objectName);
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(file.getInputStream(), file.getSize(), -1)
                .contentType(contentType)
                .build());
        String url = String.format("%s/%s/%s", minioProperties.getEndpoint(), bucketName, objectName);
        log.info("==> 上传文件至 Minio 成功,访问路径: {}", url);
        return url;
    }
 
    //删除文件:
    public boolean remove(String bucketName, String fileName) {
        /**
         * String bucketName = "test2";
         * String fileName = "/2023-04-07/16808560218465670_img.png";
         * address+bucketName+fileName 就是访问路径,删除需要后两个参数。
         */
        try {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文件删除失败");
            return false;
        }
        log.info("删除成功");
        return true;
    }
 
 
}

6.文件上传示例

public R uploadFile(MultipartFile file) {
        try {
            String fileName = file.getOriginalFilename();
            String url = minioUtil.uploadFile(file, bucketName);
            if (StringUtils.isNotEmpty(url)) {
                File fileEntity = new File();
                fileEntity.setBucketName(bucketName);
                fileEntity.setFileName(fileName);
                fileEntity.setMinioFileName(getMinioFileName(url));
                fileEntity.setFilePath(url);
                fileEntity.setCreateBy(LoginUtils.getUsername());
                fileEntity.setCreateTime(new Date());
                fileMapper.insert(fileEntity);
            }
            return R.ok(url);
        } catch (Exception e) {
            log.error("==> 上传文件异常: ", e);
            return R.fail("文件上传失败");
        }
    }

7.文件删除示例

public R remove(MinioFileDto fileDto) {
        try {
            boolean remove = minioUtil.remove(fileDto.getBucketName(), fileDto.getFileName());
            if (remove) {
                //删除数据库记录
                fileMapper.delete(new LambdaQueryWrapper<File>()
                        .eq(File::getBucketName, fileDto.getBucketName())
                        .eq(File::getMinioFileName, fileDto.getFileName()));
            }
            return R.ok();
        } catch (Exception e) {
            return R.fail("文件删除失败");
        }
    }

到此这篇关于SpringBoot集成minio实现文件上传和删除功能的文章就介绍到这了,更多相关SpringBoot minio文件上传内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文