import com.obs.services.ObsClient;
import com.obs.services.model.GetObjectRequest;
import com.obs.services.model.ObsObject;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.regex.Pattern;
public class DownloadFileForFrontend {
public static void downloadFile(String accessKey, String secretKey, String endpoint, String bucketName, String objectKey, HttpServletResponse response) {
// 初始化 ObsClient
ObsClient obsClient = new ObsClient(accessKey, secretKey, endpoint);
try {
// 创建下载请求
GetObjectRequest request = new GetObjectRequest(bucketName, objectKey);
// 获取文件对象
ObsObject obsObject = obsClient.getObject(request);
// 从 objectKey 中提取文件名
String fileName = extractFileName(objectKey);
// 设置响应头,指定文件名和内容类型等
response.setContentType(obsObject.getObjectMetadata().getContentType());
response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
// 将文件内容写入响应流
try (ServletOutputStream outputStream = response.getOutputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = obsObject.getObjectContent().read(buffer))!= -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
System.out.println("文件下载成功并发送给前端!");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 关闭 ObsClient 和资源
obsClient.close();
}
}
private static String extractFileName(String objectKey) {
Pattern pattern = Pattern.compile("/folder/(.+)");
java.util.regex.Matcher matcher = pattern.matcher(objectKey);
if (matcher.matches()) {
return matcher.group(1);
}
return "unknown_file";
}
}