Java Minio 下载文件
2023年11月1日更 推荐使用 x-file-storage框架,项目轻度集成,即可 一行代码将文件存储到OSS平台/本地。
Minio 官方文档
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")