public void downloadSlice(String bucketName, String filename, HttpServletResponse response,
HttpServletRequest request) throws Exception {
if (StringUtils.isNotBlank(filename)) {
String range = request.getHeader("Range");
//获取文件信息
StatObjectResponse statObjectResponse = minioClient.statObject(
StatObjectArgs.builder().bucket(bucketName).object(filename).build());
//开始下载位置
long startByte = 0;
//结束下载位置
long endByte = statObjectResponse.size() - 1;
//有range的话
if (StringUtils.isNotBlank(range) && range.contains("bytes=") && range.contains("-")) {
range = range.substring(range.lastIndexOf("=") + 1).trim();
String[] ranges = range.split("-");
try {
//判断range的类型
if (ranges.length == 1) {
//类型一:bytes=-2343
if (range.startsWith("-")) {
endByte = Long.parseLong(ranges[0]);
}
//类型二:bytes=2343-
else if (range.endsWith("-")) {
startByte = Long.parseLong(ranges[0]);
}
}
//类型三:bytes=22-2343
else if (ranges.length == 2) {
startByte = Long.parseLong(ranges[0]);
endByte = Long.parseLong(ranges[1]);
}
} catch (NumberFormatException e) {
startByte = 0;
endByte = statObjectResponse.size() - 1;
}
}
//要下载的长度
long contentLength = endByte - startByte + 1;
//文件类型
String contentType = request.getServletContext().getMimeType(filename);
//解决下载文件时文件名乱码问题
byte[] fileNameBytes = filename.getBytes(StandardCharsets.UTF_8);
filename = new String(fileNameBytes, 0, fileNameBytes.length, StandardCharsets.ISO_8859_1);
//各种响应头设置
//支持断点续传,获取部分字节内容:
response.setHeader("Accept-Ranges", "bytes");
//http状态码要为206:表示获取部分内容
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
response.setContentType(contentType);
response.setHeader("Last-Modified", statObjectResponse.lastModified().toString());
//inline表示浏览器直接使用,attachment表示下载,fileName表示下载的文件名
response.setHeader("Content-Disposition", "inline;filename=" + filename);
response.setHeader("Content-Length", String.valueOf(contentLength));
//Content-Range,格式为:[要下载的开始位置]-[结束位置]/[文件总大小]
response.setHeader("Content-Range", "bytes " + startByte + "-" + endByte + "/" + statObjectResponse.size());
response.setHeader("ETag", "\"".concat(statObjectResponse.etag()).concat("\""));
try {
GetObjectResponse stream = minioClient.getObject(
GetObjectArgs.builder()
.bucket(statObjectResponse.bucket())
.object(statObjectResponse.object())
.offset(startByte)
.length(contentLength)
.build());
BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream());
byte[] buffer = new byte[1024];
int len;
while ((len = stream.read(buffer)) != -1) {
os.write(buffer, 0, len);
}
os.flush();
os.close();
response.flushBuffer();
} catch (IOException e) {
e.printStackTrace();
}
}
}
09-07
6291
07-08
1795
06-10
6316
02-21
1万+
09-07