整理文件下载接口

This commit is contained in:
dftre 2024-11-14 14:02:46 +08:00
parent b94ccbb74f
commit 8b8df57553
13 changed files with 168 additions and 222 deletions

View File

@ -0,0 +1,37 @@
package com.ruoyi.common.core.domain.entity;
import java.io.InputStream;
public class FileEntity {
private InputStream fileInputSteam;
private Long byteCount;
private String filePath;
public FileEntity() {
}
public InputStream getFileInputSteam() {
return fileInputSteam;
}
public void setFileInputSteam(InputStream fileInputSteam) {
this.fileInputSteam = fileInputSteam;
}
public Long getByteCount() {
return byteCount;
}
public void setByteCount(Long byteCount) {
this.byteCount = byteCount;
}
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
}

View File

@ -15,6 +15,7 @@ import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.RuoYiConfig; import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants; import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.FileEntity;
import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException; import com.ruoyi.common.exception.file.FileNameLengthLimitExceededException;
import com.ruoyi.common.utils.DateUtils; import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils; import com.ruoyi.common.utils.StringUtils;
@ -105,11 +106,32 @@ public class DiskFileService implements FileService {
if (file.isFile() && file.exists()) { if (file.isFile() && file.exists()) {
String md5 = Md5Utils.getMd5(file); String md5 = Md5Utils.getMd5(file);
flag = file.delete(); flag = file.delete();
if(flag) { if (flag) {
FileOperateUtils.deleteFileAndMd5ByMd5(md5); FileOperateUtils.deleteFileAndMd5ByMd5(md5);
} }
} }
return flag; return flag;
} }
/**
* 获取文件
*
* @param filePath
* @return
* @throws Exception
*/
@Override
public FileEntity getFile(String filePath) throws Exception {
String localPath = RuoYiConfig.getProfile();
String downloadPath = localPath + StringUtils.substringAfter(filePath, Constants.RESOURCE_PREFIX);
File file = new File(downloadPath);
if (!file.exists()) {
throw new FileNotFoundException("未找到文件");
}
FileInputStream fileInputStream = new FileInputStream(file);
FileEntity fileEntity = new FileEntity();
fileEntity.setFileInputSteam(fileInputStream);
fileEntity.setByteCount(file.length());
return fileEntity;
};
} }

View File

@ -5,6 +5,8 @@ import java.io.InputStream;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.core.domain.entity.FileEntity;
//默认上传下载 //默认上传下载
/** /**
* 文件操作接口 * 文件操作接口
@ -74,4 +76,13 @@ public interface FileService {
* *
*/ */
public boolean deleteFile(String filePath) throws Exception; public boolean deleteFile(String filePath) throws Exception;
/**
* 获取文件
*
* @param filePath
* @return
* @throws Exception
*/
public FileEntity getFile(String filePath) throws Exception;
} }

View File

@ -51,6 +51,7 @@ public class MinioConfig implements InitializingBean {
.stream(EmptyInputStream.nullInputStream(), 0, -1).bucket(minioBucket.getBuketName()).build(); .stream(EmptyInputStream.nullInputStream(), 0, -1).bucket(minioBucket.getBuketName()).build();
minioBucket.getClient().putObject(putObjectArgs); minioBucket.getClient().putObject(putObjectArgs);
} catch (Exception e) { } catch (Exception e) {
logger.error("数据桶:{} - 链接失败", minioBucket.getName());
throw new RuntimeException(e.getMessage()); throw new RuntimeException(e.getMessage());
} }
if (!b) { if (!b) {

View File

@ -14,9 +14,7 @@ import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.middleware.minio.domain.MinioFileVO; import com.ruoyi.middleware.minio.domain.MinioFileVO;
import com.ruoyi.middleware.minio.utils.MinioUtil; import com.ruoyi.middleware.minio.utils.MinioUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
import okhttp3.Headers;
@RestController @RestController
@RequestMapping("/minio") @RequestMapping("/minio")
@ -24,20 +22,20 @@ public class MinioController {
@GetMapping("/{client}") @GetMapping("/{client}")
@Anonymous @Anonymous
public void downLoadFile(HttpServletRequest request, HttpServletResponse response, public void downLoadFile(HttpServletResponse response,
@PathVariable("client") String client, @PathVariable("client") String client,
@RequestParam("fileName") String fileName) throws Exception { @RequestParam("fileName") String fileName) throws Exception {
MinioFileVO file = MinioUtil.getFile(client, fileName); MinioFileVO file = MinioUtil.getFile(client, fileName);
Headers headers = file.getHeaders(); FileUtils.setAttachmentResponseHeader(response, FileUtils.getName(fileName));
String contentType = headers.get("content-Type"); response.setContentLengthLong(file.getByteCount());
response.setContentType(contentType);
FileUtils.writeBytes(file.getFileInputSteam(), response.getOutputStream()); FileUtils.writeBytes(file.getFileInputSteam(), response.getOutputStream());
} }
@PutMapping("/{client}") @PutMapping("/{client}")
@Anonymous @Anonymous
public String uploadFile(HttpServletRequest request, HttpServletResponse response, public String uploadFile(
@PathVariable("client") String client, @RequestBody MultipartFile file) throws Exception { @PathVariable("client") String client,
@RequestBody MultipartFile file) throws Exception {
return MinioUtil.uploadFile(client, file); return MinioUtil.uploadFile(client, file);
} }
} }

View File

@ -1,12 +1,10 @@
package com.ruoyi.middleware.minio.domain; package com.ruoyi.middleware.minio.domain;
import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.middleware.minio.config.MinioConfig;
import com.ruoyi.middleware.minio.exception.MinioClientErrorException; import com.ruoyi.middleware.minio.exception.MinioClientErrorException;
import io.minio.GetObjectArgs; import io.minio.GetObjectArgs;
@ -14,7 +12,6 @@ import io.minio.GetObjectResponse;
import io.minio.MinioClient; import io.minio.MinioClient;
import io.minio.PutObjectArgs; import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs; import io.minio.RemoveObjectArgs;
import com.ruoyi.common.exception.file.FileException;
public class MinioBucket { public class MinioBucket {
@ -77,25 +74,6 @@ public class MinioBucket {
this.client.removeObject(removeObjectArgs); this.client.removeObject(removeObjectArgs);
} }
public MinioFileVO get(GetObjectArgs getObjectArgs) throws Exception {
GetObjectResponse inputStream = this.client.getObject(getObjectArgs);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[MinioConfig.maxSize];
int length = 0;
while (true) {
try {
if (!((length = inputStream.read(bytes, 0, bytes.length)) > 0)) {
break;
}
} catch (Exception e) {
throw new FileException("500", new String[] { e.getMessage() });
}
byteArrayOutputStream.write(bytes, 0, length);
}
return new MinioFileVO(inputStream, inputStream.object(), inputStream.headers(), inputStream.bucket(),
inputStream.region());
}
/** /**
* 文件下载 * 文件下载
* *
@ -105,7 +83,17 @@ public class MinioBucket {
* @throws IOException 比如读写文件出错时 * @throws IOException 比如读写文件出错时
*/ */
public MinioFileVO get(String filePath) throws Exception { public MinioFileVO get(String filePath) throws Exception {
GetObjectArgs build = GetObjectArgs.builder().object(filePath).bucket(buketName).build(); GetObjectArgs getObjectArgs = GetObjectArgs.builder().object(filePath).bucket(buketName).build();
return get(build); GetObjectResponse inputStream = this.client.getObject(getObjectArgs);
MinioFileVO minioFileVO = new MinioFileVO();
minioFileVO.setFileInputSteam(inputStream);
minioFileVO.setByteCount(inputStream.headers().byteCount());
minioFileVO.setFilePath(filePath);
minioFileVO.setObject(inputStream.object());
minioFileVO.setRegion(inputStream.region());
minioFileVO.setBuket(inputStream.bucket());
minioFileVO.setHeaders(inputStream.headers());
return minioFileVO;
} }
} }

View File

@ -1,25 +1,17 @@
package com.ruoyi.middleware.minio.domain; package com.ruoyi.middleware.minio.domain;
import com.ruoyi.common.core.domain.entity.FileEntity;
import okhttp3.Headers; import okhttp3.Headers;
import java.io.InputStream; public class MinioFileVO extends FileEntity {
public class MinioFileVO {
private InputStream fileInputSteam;
private String object; private String object;
private Headers headers; private Headers headers;
private String buket; private String buket;
private String region; private String region;
public MinioFileVO() { public MinioFileVO() {
} super();
public InputStream getFileInputSteam() {
return fileInputSteam;
}
public void setFileInputSteam(InputStream fileInputSteam) {
this.fileInputSteam = fileInputSteam;
} }
public String getObject() { public String getObject() {
@ -54,12 +46,4 @@ public class MinioFileVO {
this.region = region; this.region = region;
} }
public MinioFileVO(InputStream fileInputSteam, String object, Headers headers, String buket, String region) {
this.fileInputSteam = fileInputSteam;
this.object = object;
this.headers = headers;
this.buket = buket;
this.region = region;
}
} }

View File

@ -9,6 +9,7 @@ import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.RuoYiConfig; import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.FileEntity;
import com.ruoyi.common.service.file.FileService; import com.ruoyi.common.service.file.FileService;
import com.ruoyi.common.utils.file.FileOperateUtils; import com.ruoyi.common.utils.file.FileOperateUtils;
import com.ruoyi.common.utils.file.FileUtils; import com.ruoyi.common.utils.file.FileUtils;
@ -65,4 +66,16 @@ public class MinioFileService implements FileService {
FileOperateUtils.deleteFileAndMd5ByFilePath(filePath); FileOperateUtils.deleteFileAndMd5ByFilePath(filePath);
return true; return true;
} }
/**
* 获取文件
*
* @param filePath
* @return
* @throws Exception
*/
@Override
public FileEntity getFile(String filePath) throws Exception {
return MinioUtil.getFile(minioConfig.getPrimary(), filePath);
};
} }

View File

@ -1,11 +1,5 @@
package com.ruoyi.alibaba.oss.controller; package com.ruoyi.alibaba.oss.controller;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.PutMapping;
@ -16,53 +10,33 @@ import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.alibaba.oss.domain.AliOssFileVO; import com.ruoyi.alibaba.oss.domain.AliOssFileVO;
import com.ruoyi.alibaba.oss.utils.AliOssUtil; import com.ruoyi.alibaba.oss.utils.AliOssUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.utils.file.FileUtils;
import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse; import jakarta.servlet.http.HttpServletResponse;
@RestController @RestController
@RequestMapping("/oss") @RequestMapping("/oss")
public class AliOssController { public class AliOssController {
@Autowired
private AliOssUtil aliOssUtil;
@Operation(summary = "下载接口oss") @Operation(summary = "下载接口oss")
@GetMapping("/{client}") @GetMapping("/{client}")
public void downLoadFile(HttpServletRequest request, HttpServletResponse response,@PathVariable("client") String client, @Anonymous
@RequestParam("fileName") String fileName) throws Exception { public void downLoadFile(HttpServletResponse response,
AliOssFileVO file = aliOssUtil.getFile(client, fileName); @PathVariable("client") String client,
// 设置响应头 @RequestParam("fileName") String fileName) throws Exception {
String contentType = file.getHeaders().getOrDefault("Content-Type", "application/octet-stream"); AliOssFileVO file = AliOssUtil.getFile(client, fileName);
response.setContentType(contentType); FileUtils.setAttachmentResponseHeader(response, FileUtils.getName(fileName));
response.setContentLengthLong(file.getByteCount());
// 设置内容长度 FileUtils.writeBytes(file.getFileInputSteam(), response.getOutputStream());
String contentLength = file.getHeaders().get("Content-Length");
if (contentLength != null) {
response.setContentLengthLong(Long.parseLong(contentLength));
}
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"");
// 写入文件内容到响应流
try (InputStream inputStream = file.getFileInputSteam();
OutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
} catch (IOException e) {
throw new IOException("Error writing file to output stream", e);
}
} }
// 上传接口
//上传接口
@Operation(summary = "上传接口oss") @Operation(summary = "上传接口oss")
@PutMapping("/{client}") @PutMapping("/{client}")
public String uploadFile(HttpServletRequest request, HttpServletResponse response, public String uploadFile(@PathVariable("client") String client, @RequestParam("file") MultipartFile file)
@PathVariable("client") String client, @RequestParam("file") MultipartFile file) throws Exception { throws Exception {
return AliOssUtil.uploadFile(client, file); return AliOssUtil.uploadFile(client, file);
} }
} }

View File

@ -1,11 +1,7 @@
package com.ruoyi.alibaba.oss.domain; package com.ruoyi.alibaba.oss.domain;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream; import java.io.InputStream;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -61,7 +57,7 @@ public class AliOssBucket {
// 创建 ObjectMetadata 对象并设置内容类型 // 创建 ObjectMetadata 对象并设置内容类型
ObjectMetadata metadata = new ObjectMetadata(); ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(contentType); metadata.setContentType(contentType);
metadata.setContentLength(inputStream.available()); // 使用 InputStream available 方法 metadata.setContentLength(inputStream.available()); // 使用 InputStream available 方法
// 创建 PutObjectRequest 对象 // 创建 PutObjectRequest 对象
PutObjectRequest putRequest = new PutObjectRequest(bucketName, filePath, inputStream, metadata); PutObjectRequest putRequest = new PutObjectRequest(bucketName, filePath, inputStream, metadata);
@ -99,43 +95,6 @@ public class AliOssBucket {
} }
} }
public AliOssFileVO get(GetObjectRequest getObjectRequest) throws Exception {
try (OSSObject ossObject = this.ossClient.getObject(getObjectRequest)) {
if (ossObject == null) {
throw new Exception("Failed to retrieve object from OSS.");
}
// 读取OSSObject的内容到ByteArrayOutputStream中
try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
byte[] bytes = new byte[1024]; // 根据需要调整缓冲区大小
int length;
while ((length = ossObject.getObjectContent().read(bytes)) != -1) {
byteArrayOutputStream.write(bytes, 0, length);
}
// 获取 headers
Map<String, String> headers = new HashMap<>();
for (Map.Entry<String, String> entry : ossObject.getObjectMetadata().getUserMetadata().entrySet()) {
headers.put(entry.getKey(), entry.getValue());
}
headers.put("Content-Type", ossObject.getObjectMetadata().getContentType());
headers.put("Content-Length", String.valueOf(ossObject.getObjectMetadata().getContentLength()));
// 设置 AliOssFileVO 对象的属性
AliOssFileVO fileVO = new AliOssFileVO();
fileVO.setFileInputSteam(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
fileVO.setHeaders(headers);
fileVO.setKey(ossObject.getKey());
fileVO.setBucketName(ossObject.getBucketName());
return fileVO;
}
} catch (Exception e) {
logger.error("Error retrieving file: {}", e.getMessage(), e);
throw new AliOssClientErrorException("Error retrieving file: " + e.getMessage(), e);
}
}
/** /**
* 文件下载 * 文件下载
* *
@ -145,6 +104,16 @@ public class AliOssBucket {
*/ */
public AliOssFileVO get(String filePath) throws Exception { public AliOssFileVO get(String filePath) throws Exception {
GetObjectRequest request = new GetObjectRequest(this.bucketName, filePath); GetObjectRequest request = new GetObjectRequest(this.bucketName, filePath);
return get(request); OSSObject ossObject = this.ossClient.getObject(request);
if (ossObject == null) {
throw new Exception("Failed to retrieve object from OSS.");
}
// 设置 AliOssFileVO 对象的属性
AliOssFileVO fileVO = new AliOssFileVO();
fileVO.setFileInputSteam(ossObject.getObjectContent());
fileVO.setKey(ossObject.getKey());
fileVO.setBucketName(ossObject.getBucketName());
fileVO.setByteCount(ossObject.getObjectMetadata().getContentLength());
return fileVO;
} }
} }

View File

@ -1,29 +1,14 @@
package com.ruoyi.alibaba.oss.domain; package com.ruoyi.alibaba.oss.domain;
import java.io.InputStream; import com.aliyun.oss.model.ObjectMetadata;
import java.util.Map; import com.ruoyi.common.core.domain.entity.FileEntity;
public class AliOssFileVO { public class AliOssFileVO extends FileEntity {
private InputStream fileInputSteam;
private String key; private String key;
private Map<String, String> headers;
private String bucketName; private String bucketName;
private ObjectMetadata metadata;
public AliOssFileVO(){} public AliOssFileVO() {
public AliOssFileVO(InputStream fileInputSteam, String key, Map<String, String> headers, String bucketName) {
this.fileInputSteam = fileInputSteam;
this.key = key;
this.headers = headers;
this.bucketName = bucketName;
}
public InputStream getFileInputSteam() {
return fileInputSteam;
}
public void setFileInputSteam(InputStream fileInputSteam) {
this.fileInputSteam = fileInputSteam;
} }
public String getKey() { public String getKey() {
@ -34,14 +19,6 @@ public class AliOssFileVO {
this.key = key; this.key = key;
} }
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public String getBucketName() { public String getBucketName() {
return bucketName; return bucketName;
} }
@ -49,4 +26,12 @@ public class AliOssFileVO {
public void setBucketName(String bucketName) { public void setBucketName(String bucketName) {
this.bucketName = bucketName; this.bucketName = bucketName;
} }
public ObjectMetadata getMetadata() {
return metadata;
}
public void setMetadata(ObjectMetadata metadata) {
this.metadata = metadata;
}
} }

View File

@ -12,6 +12,7 @@ import com.ruoyi.alibaba.oss.config.AliOssConfig;
import com.ruoyi.alibaba.oss.domain.AliOssFileVO; import com.ruoyi.alibaba.oss.domain.AliOssFileVO;
import com.ruoyi.alibaba.oss.utils.AliOssUtil; import com.ruoyi.alibaba.oss.utils.AliOssUtil;
import com.ruoyi.common.config.RuoYiConfig; import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.FileEntity;
import com.ruoyi.common.service.file.FileService; import com.ruoyi.common.service.file.FileService;
import com.ruoyi.common.utils.file.FileOperateUtils; import com.ruoyi.common.utils.file.FileOperateUtils;
import com.ruoyi.common.utils.file.FileUtils; import com.ruoyi.common.utils.file.FileUtils;
@ -68,6 +69,18 @@ public class AliOssFileService implements FileService {
return true; return true;
} }
/**
* 获取文件
*
* @param filePath
* @return
* @throws Exception
*/
@Override
public FileEntity getFile(String filePath) throws Exception {
return AliOssUtil.getFile(filePath);
};
/** /**
* 提取文件名 * 提取文件名
* *

View File

@ -1,17 +1,10 @@
package com.ruoyi.alibaba.oss.utils; package com.ruoyi.alibaba.oss.utils;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
import com.aliyun.oss.OSS;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;
import com.ruoyi.alibaba.oss.config.AliOssConfig; import com.ruoyi.alibaba.oss.config.AliOssConfig;
import com.ruoyi.alibaba.oss.domain.AliOssBucket; import com.ruoyi.alibaba.oss.domain.AliOssBucket;
import com.ruoyi.alibaba.oss.domain.AliOssFileVO; import com.ruoyi.alibaba.oss.domain.AliOssFileVO;
@ -43,13 +36,14 @@ public class AliOssUtil {
/** /**
* 文件上传 * 文件上传
* *
* @param client 连接名 * @param client 连接名
* @param file 上传的文件 * @param file 上传的文件
* @return 返回上传成功的文件名 * @return 返回上传成功的文件名
* @throws IOException 比如读写文件出错时 * @throws IOException 比如读写文件出错时
*/ */
public static String uploadFile(String client, MultipartFile file) throws Exception { public static String uploadFile(String client, MultipartFile file) throws Exception {
String fileName = DateUtils.dateTimeNow() + UUID.fastUUID().toString().substring(0, 5) + "." + FileUtils.getExtension(file); String fileName = DateUtils.dateTimeNow() + UUID.fastUUID().toString().substring(0, 5) + "."
+ FileUtils.getExtension(file);
return uploadFile(client, fileName, file); return uploadFile(client, fileName, file);
} }
@ -126,57 +120,14 @@ public class AliOssUtil {
* @throws IOException 比如读写文件出错时 * @throws IOException 比如读写文件出错时
*/ */
public static AliOssFileVO getFile(String client, String filePath) throws Exception { public static AliOssFileVO getFile(String client, String filePath) throws Exception {
AliOssBucket ossBucket = client == null ? getAliOssConfig().getMasterBucket() : getAliOssConfig().getBucket(client); AliOssBucket ossBucket = client == null ? getAliOssConfig().getMasterBucket()
String bucketName = client == null ? getAliOssConfig().getMasterBucketName() : getAliOssConfig().getBucketName(client); : getAliOssConfig().getBucket(client);
String bucketName = client == null ? getAliOssConfig().getMasterBucketName()
: getAliOssConfig().getBucketName(client);
if (bucketName == null) { if (bucketName == null) {
throw new AliOssClientErrorException("参数 \"bucketName\" 为空指针"); throw new AliOssClientErrorException("参数 \"bucketName\" 为空指针");
} }
return ossBucket.get(filePath);
GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, filePath);
return get(getObjectRequest, ossBucket.getOssClient());
}
/**
* 从OSS中获取文件并封装成AliOssFileVO对象
*
* @param getObjectRequest 获取对象请求
* @param ossClient OSS客户端
* @return 返回封装的Oss下载文件对象
* @throws Exception 如果获取文件失败
*/
private static AliOssFileVO get(GetObjectRequest getObjectRequest, OSS ossClient) throws Exception {
OSSObject ossObject = ossClient.getObject(getObjectRequest);
if (ossObject == null) {
throw new Exception("Failed to retrieve object from OSS.");
}
// 读取OSSObject的内容到ByteArrayOutputStream中
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[1024]; // 根据需要调整缓冲区大小
int length;
while ((length = ossObject.getObjectContent().read(bytes)) != -1) {
byteArrayOutputStream.write(bytes, 0, length);
}
// 获取 headers
Map<String, String> headers = new HashMap<>();
for (Map.Entry<String, String> entry : ossObject.getObjectMetadata().getUserMetadata().entrySet()) {
headers.put(entry.getKey(), entry.getValue());
}
headers.put("Content-Type", ossObject.getObjectMetadata().getContentType());
headers.put("Content-Length", String.valueOf(ossObject.getObjectMetadata().getContentLength()));
// 设置 AliOssFileVO 对象的属性
AliOssFileVO fileVO = new AliOssFileVO();
fileVO.setFileInputSteam(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()));
fileVO.setHeaders(headers);
fileVO.setKey(ossObject.getKey());
fileVO.setBucketName(ossObject.getBucketName());
// 关闭OSSObject
ossObject.close();
return fileVO;
} }
} }