正在阅读:
- 首页 » 开发运维 » 后端 » springboot 整合Minio下载文件(文件流)
springboot 整合Minio下载文件(文件流)
springboot 整合Minio下载文件(文件流)
maven(pom文件)引入 minio包
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>4.0.0</version>
</dependency>
2.代码:
import com.baomidou.mybatisplus.core.conditions.Wrapper; import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.wh.common.exception.WhBusinessException; import com.wh.modules.shared.entity.MinioFile; import com.wh.modules.shared.service.IMinioFileService; import io.minio.MinioClient; import lombok.extern.slf4j.Slf4j; import org.apache.tomcat.util.http.fileupload.IOUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.InputStream; import java.util.Arrays; import java.util.Iterator; import java.util.List; @RestController @RequestMapping("/sys/minio") @Slf4j public class MinioDemoController { @Autowired private IMinioFileService minioFileService; //minio服务的IP端口、用户名、密码、文件存放包名 @Value(value = "${minio.minio_url}") private String url; @Value(value = "${minio.minio_name}") private String accessKey; @Value(value = "${minio.minio_pass}") private String secretKey; @Value(value = "${minio.bucketName}") private String bucketName; @GetMapping({"/download"}) public void getFile(String id, HttpServletRequest req, HttpServletResponse response) { QueryWrapper<MinioFile> queryWrapper = new QueryWrapper(); List<String> idList = Arrays.asList(id.split(",")); List<MinioFile> pageList = this.minioFileService.list((Wrapper)queryWrapper.in("id", idList)); if (pageList.size() != idList.size()) { throw new WhBusinessException(404, "无法定位到文件!"); } else { try { MinioClient minioClient = new MinioClient(this.url, this.accessKey, this.secretKey); Iterator var8 = pageList.iterator(); while(var8.hasNext()) { MinioFile minioFile = (MinioFile)var8.next(); String fileName = minioFile.getFileName().replace("\r\n", ""); InputStream fileInputStream = minioClient.getObject(this.bucketName, fileName); response.setContentType("application/force-download"); response.setHeader("Content-Disposition", "attachment;filename=\"$ObjectName\""); response.setCharacterEncoding("UTF-8"); IOUtils.copy(fileInputStream, response.getOutputStream()); } } catch (Exception var12) { var12.printStackTrace(); throw new WhBusinessException(502, "下载失败"); } } } }
3.说明
其中 用到了 mybatis puls ,以及将文件信息存放到数据库中的方式,下载时,获取到文件信息,再通过设置的MINIo地址,获取文件并转换成文件流返回到前端。
前端下载代码:直通车
该日志由 bemender 于 2021年03月17日 发表
转载请注明文本地址:https://www.bemhome.com/post/109.html