Java Minio 下载文件

Java Minio 下载文件

2023年11月1日更 推荐使用 x-file-storage框架,项目轻度集成,即可 一行代码将文件存储到OSS平台/本地。

Minio 官方文档

Minio SDK Java API 文档

minio 文件地址:http://192.168.31.1:9000/bucketName/20221011/1596681603481809.png
存储桶名称 :bucketName (代码中的MINIO_BUCKET_NAME)
文件地址:20200806/1596681603481809.png

JAVA



	@SneakyThrows
	@GetMapping("/down-file")
	public void downProtectFile(String fileName, String path, HttpServletResponse response) {
		if (StringUtil.isNotBlank(name) && StringUtil.isNotBlank(url)) {
		//自行封装minioClient
		MinioClient minioClient = MinioClient.builder()
				.endpoint(oss.getEndpoint())
				.credentials(oss.getAccessKey(), oss.getSecretKey())
				.build();
//			文件不存在,会抛出异常
			OssFile ossFile = minioClient.statObject(StatObjectArgs.builder().bucket(MINIO_BUCKET_NAME).object(path).build());
			
//			获取文件流
			InputStream object = minioClient.getObject(GetObjectArgs.builder().bucket(MINIO_BUCKET_NAME).object(path).build());
			OutputStream outputStream = null;
			try {
				byte[] buf = new byte[1024];
				int length = 0;
				response.reset();
				response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
				response.setContentType("application/octet-stream");
				response.setCharacterEncoding("UTF-8");
				outputStream = response.getOutputStream();
				// 输出文件
				while ((length = object.read(buf)) > 0) {
					outputStream.write(buf, 0, length);
				}

			} catch (Exception ex) {
				response.setHeader("Content-type", "text/html;charset=UTF-8");
				String data = "文件下载失败";
				OutputStream ps = response.getOutputStream();
				ps.write(data.getBytes("UTF-8"));
			} finally {
				// 关闭输出流
				if (object != null) {
					object.close();
				}
				if (outputStream != null) {
					outputStream.close();
				}

			}
		}

	}

JS工具类

export const downloadFileBlob = (path, name) => {
  const xhr = new XMLHttpRequest();
  xhr.open('get', path);
  xhr.responseType = 'blob';
  xhr.send();
  xhr.onload = function () {
    if (this.status === 200 || this.status === 304) {
      // 如果是IE10及以上,不支持download属性,采用msSaveOrOpenBlob方法,但是IE10以下也不支持msSaveOrOpenBlob
      if ('msSaveOrOpenBlob' in navigator) {
        navigator.msSaveOrOpenBlob(this.response, name);
        return;
      }
      const url = URL.createObjectURL(this.response);
      const a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = name;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
      Message({
        message: "[" + name + "]正在下载中,请稍候...",
        type: 'success'
      });
    } else {
      Message({
        message: "文件不存在,请联系管理员确认!",
        type: 'error'
      });
    }
  };
  xhr.onerror = function () {
    Message({
      message: "文件下载失败,请稍后重试!",
      type: 'warning'
    });
  };
}

//使用方式
 downloadFileBlob(`/api/down-file?name=test.txt&url=20221011/1596681603481809.png`,"自定义文件名称.xlsx")
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值