springboot使用minio进行文件上传下载

安装minio参考Docker 搭建 MinIO_letterss的博客-CSDN博客 

 pom

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

 application.properties

#minio配置
minio.endpoint= http://192.168.32.1:9000
minio.accesskey= minio
minio.secretKey= minio

minio配置类 

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * auth: ws
 *
 * minio配置类
 */
@Data
@Component
public class MinioProp {
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.accesskey}")
    private String accesskey;
    @Value("${minio.secretKey}")
    private String secretKey;

}

minio客户端配置

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

import javax.annotation.Resource;

/**
 * auth: ws
 * <p>
 * minio客户端配置
 */
@Configuration
public class MinioConfiguration {
    @Resource
    private MinioProp minioProp;

    @Bean
    public MinioClient minioClient() {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioProp.getEndpoint())
                .credentials(minioProp.getAccesskey(), minioProp.getSecretKey())
                .build();
        return minioClient;
    }

}

 数据库

CREATE TABLE `file_manage` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `file_name` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '文件名称',
  `file_id` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '文件id',
  `bucket` varchar(255) COLLATE utf8_bin DEFAULT NULL COMMENT '存储桶',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

实体类

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * <p>
 * 文件管理
 * </p>
 *
 * @author ws
 * @since 2021-11-18
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
@ApiModel(value="FileManage对象", description="文件管理")
public class FileManage implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    @ApiModelProperty(value = "文件名称")
    private String fileName;

    @ApiModelProperty(value = "文件id")
    private String fileId;

    @ApiModelProperty(value = "存储桶")
    private String bucket;

    @ApiModelProperty(value = "创建时间")
    @TableField(fill = FieldFill.INSERT)
    private Date createTime;


    public FileManage(String fileName, String fileId, String bucket, Date createTime) {
        this.fileName = fileName;
        this.fileId = fileId;
        this.bucket = bucket;
        this.createTime = createTime;
    }
}

mapper

public interface FileManageMapper  extends BaseMapper<FileManage> {
}

service

/**
 * <p>
 * 文件管理 服务类
 * </p>
 *
 * @author ws
 * @since 2021-11-18
 */
public interface IFileManageService extends IService<FileManage> {
    List<FileManage> getRelFileName(List<String> list);
}

 serviceImpl

/**
 * <p>
 * 文件管理 服务实现类
 * </p>
 *
 * @author ws
 * @since 2021-11-18
 */
@Service
public class FileManageServiceImpl extends ServiceImpl<FileManageMapper, FileManage> implements IFileManageService {
    /**
     * 根据文件唯一标识,查询文件名
     * @param list
     * @return
     */
    @Override
    public List<FileManage> getRelFileName(List<String> list){
        QueryWrapper<FileManage> fileInfoQueryWrapper = new QueryWrapper<>();
        fileInfoQueryWrapper.in("file_id",list).select("file_id","file_name","bucket");
        List<FileManage> platformFileInfos = this.list(fileInfoQueryWrapper);
        return platformFileInfos;
    }
}
BaseException
public class BaseException extends RuntimeException
{
    private static final long serialVersionUID = 1L;

    /**
     * 所属模块
     */
    private String module;

    /**
     * 错误码
     */
    private String code;

    /**
     * 错误码对应的参数
     */
    private Object[] args;

    /**
     * 错误消息
     */
    private String defaultMessage;

    public BaseException(String module, String code, Object[] args, String defaultMessage)
    {
        this.module = module;
        this.code = code;
        this.args = args;
        this.defaultMessage = defaultMessage;
    }

    public BaseException(String module, String code, Object[] args)
    {
        this(module, code, args, null);
    }

    public BaseException(String module, String defaultMessage)
    {
        this(module, null, null, defaultMessage);
    }

    public BaseException(String code, Object[] args)
    {
        this(null, code, args, null);
    }

    public BaseException(String defaultMessage)
    {
        this(null, null, null, defaultMessage);
    }

    public String getModule()
    {
        return module;
    }

    public String getCode()
    {
        return code;
    }

    public Object[] getArgs()
    {
        return args;
    }

    public String getDefaultMessage()
    {
        return defaultMessage;
    }
}

方法工具类

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.flink.streaming.web.common.RestResult;
import com.flink.streaming.web.common.util.BaseException;
import com.flink.streaming.web.model.entity.FileManage;
import com.flink.streaming.web.service.IFileManageService;
import io.minio.*;
import io.minio.messages.Bucket;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.*;

/**
 * auth: ws
 * <p>
 * 文件服务
 */
@Slf4j
@RestController
@RequestMapping("/file")
@Api(value = "/file", description = "文件服务")
public class FileController {
    @Autowired
    private MinioClient minioClient;

    @Autowired
    IFileManageService fileInfoService;

    @ApiOperation("上传文件")
    @PostMapping("/upload")
    public RestResult upload(@RequestParam(name = "file", required = false) MultipartFile[] file, @RequestParam(name = "bucket") String bucket) {
        if (file == null || file.length == 0) {
            return RestResult.error("上传文件不能为空");
        }
        if (StringUtils.isBlank(bucket)) {
            return RestResult.error("文件桶不能为空");
        }
        List<String> orgfileNameList = new ArrayList<>(file.length);

        for (MultipartFile multipartFile : file) {
            String orgfileName = multipartFile.getOriginalFilename();
            String fileId =UUID.randomUUID().toString().replaceAll("-","");
            try {
                InputStream in = multipartFile.getInputStream();
                //minioClient.putObject(minioBucket, orgfileName, in, new PutObjectOptions(in.available(), -1));
                ObjectWriteResponse objectWriteResponse = minioClient.putObject(
                        PutObjectArgs.builder()
                                .bucket(bucket)
                                .object(fileId)
                                .stream(in, in.available(), -1)
                                .build());
                in.close();
                boolean save = fileInfoService.save(new FileManage(orgfileName, fileId, bucket, new Date()));
                if (!save) {
                    log.error("文件保存数据库失败, bucket: {} fileId: {} fileName: {}", bucket, fileId, orgfileName);
                    return RestResult.error("文件保存数据库失败");
                }
                orgfileNameList.add(fileId);
            } catch (Exception e) {
                log.error(e.getMessage());
                return RestResult.error("上传失败");
            }
        }

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("bucketName", bucket);
        data.put("fileName", orgfileNameList);
        return RestResult.success(data);
    }

    @ApiOperation("列出buckets列表")
    @GetMapping("/listBuckets")
    public RestResult<List<String>> listBuckets() {
        List<Bucket> bucketList = null;
        try {
            bucketList = minioClient.listBuckets();
        } catch (Exception e) {
            log.error(e.getMessage());
            return RestResult.error("获取文件桶列表失败");
        }
        ArrayList<String> ret = new ArrayList<>();
        for (Bucket bucket : bucketList) {
            ret.add(bucket.name());
        }
        return RestResult.success(ret);
    }


    @ApiOperation("获取资源文件")
    @GetMapping(value = {"/download/{fileId}"})
    public void download(HttpServletResponse response, @PathVariable("fileId") String fileId) {
        try {
            QueryWrapper<FileManage> fileInfoQueryWrapper = new QueryWrapper<>();
            HashMap<String, String> queryMap = new HashMap<>();
            queryMap.put("file_id", fileId);
            FileManage fileInfo = fileInfoService.getOne(fileInfoQueryWrapper.allEq(queryMap, false));
            if (fileInfo == null) {
                throw new BaseException("资源不存在");
            }
            //response.setContentType(stat.contentType());
            GetObjectResponse getObjectResponse =
                    minioClient.getObject(
                            GetObjectArgs.builder().bucket(fileInfo.getBucket()).object(fileId).build());
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileInfo.getFileName(), "UTF-8"));
            IOUtils.copy(getObjectResponse, response.getOutputStream());
        } catch (Exception e) {
            log.error(e.getMessage());
        }
    }

    @ApiOperation("删除资源文件")
    @DeleteMapping(value = {"/del/{bucket}/{fileId}"})
    public RestResult delete(@PathVariable(value = "bucket") String bucket, @PathVariable("fileId") String fileId) {
        try {
            QueryWrapper<FileManage> fileInfoQueryWrapper = new QueryWrapper<>();
            HashMap<String, String> queryMap = new HashMap<>();
            queryMap.put("file_id", fileId);
            queryMap.put("bucket", bucket);
            fileInfoService.remove(fileInfoQueryWrapper.allEq(queryMap, false));
            minioClient.removeObject(
                    RemoveObjectArgs.builder()
                            .bucket(bucket)
                            .object(fileId)
                            .build()
            );
        } catch (Exception e) {
            log.error(e.getMessage());
            return RestResult.error("删除失败");
        }
        return RestResult.success();
    }

    @ApiOperation("根据文件标识获取文件名")
    @PostMapping(value = {"/query"})
    public RestResult<List<FileManage>> query(@RequestBody List<String> fileIds) {
        List<FileManage> relFileNames = fileInfoService.getRelFileName(fileIds);
        return RestResult.success(relFileNames);
    }


}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要实现Spring Boot与Minio的大文件上传并解压的功能,可以按照以下步骤进行操作: 1. 首先,在Spring Boot项目的pom.xml文件中引入Minio的依赖。可以使用以下代码将Minio的依赖添加到项目中: ``` <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.2.1</version> </dependency> ``` 2. 然后,将大文件分片并上传到Minio对象存储服务。可以按照以下步骤进行操作: - 将要上传的大文件进行分片处理,可以使用文件分片算法将大文件分成多个小块。 - 将分片后的文件依次上传到Minio对象存储服务,并指定一个临时文件名。 3. 分片上传完成后,将所有分片合并为一个完整的文件。可以按照以下步骤进行操作: - 从Minio中读取所有分片文件的流。 - 将分片流写入到一个临时文件中,以便后续解压。 4. 解压临时文件。可以按照以下步骤进行操作: - 使用合适的解压库或工具,对临时文件进行解压。 - 解压后的文件可以按需求进行进一步处理,例如再次上传到Minio或其他存储系统。 综上所述,要实现Spring Boot与Minio的大文件上传并解压功能,需要将文件分片并上传到Minio,然后将分片合并为完整文件,最后解压文件。这样可以实现大文件的上传和解压操作。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [Spring boot + minio 分片上传](https://blog.csdn.net/XIAOTONGZHU/article/details/130346735)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [SpringBoot 使用 Minio 进行文件存储](https://blog.csdn.net/qq_43692950/article/details/125961685)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [Windows常用软件压缩包,后端Java适用于springboot 2.6.x等高版本](https://download.csdn.net/download/m0_55710969/85062866)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

今朝花落悲颜色

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值