package org.springblade.sample.utils;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProvider;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.*;
import java.net.URLEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springblade.core.log.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.servlet.http.HttpServletResponse;
@Slf4j
@Configuration
public class OssUtils {
@Value("${oss.access_key:''}")
private String access_key;
@Value("${oss.secret_key:''}")
private String secret_key;
@Value("${oss.endpoint:''}")
private String endpoint;
@Value("${oss.bucket:''}")
private String bucket;
@Value("${oss.region:''}")
private String region;
/**
* 上传oss
*
* @param filePath 本地文件路径
* @param ossPath oss存放路径
*/
public void uploadFile(String filePath, String ossPath) {
OSS ossClient = null;
File file = new File(filePath);
try (FileInputStream inputStream = new FileInputStream(file)) {
// 创建OSSClient实例。
CredentialsProvider credentialsProvider = new DefaultCredentialProvider(access_key, secret_key);
ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
// 创建PutObjectRequest请求。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, ossPath, inputStream);
// 上传文件。
ossClient.putObject(putObjectRequest);
} catch (Exception e) {
log.error("文件上传失败文件路径: {} 错误信息: {}", filePath, e);
throw new ServiceException(e.getMessage());
} finally {
// 关闭OSSClient。
if (ossClient != null) {
ossClient.shutdown();
}
}
}
/**
* 流式文件下载(阿里云Oss)
*
* @param objectName 阿里云文件存储路径
* @param response 输出流
*/
public void downloadFile(String objectName, HttpServletResponse response) {
CredentialsProvider credentialsProvider = new DefaultCredentialProvider(access_key, secret_key);
// 创建OSSClient实例
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
clientBuilderConfiguration.setSignatureVersion(SignVersion.V2);
OSS ossClient = OSSClientBuilder.create().endpoint(endpoint).credentialsProvider(credentialsProvider).clientConfiguration(clientBuilderConfiguration).region(region).build();
OSSObject ossObject = ossClient.getObject(bucket, objectName);
try (InputStream inputStream = ossObject.getObjectContent(); OutputStream os = response.getOutputStream()) {
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(objectName, "UTF-8") + "\"");
// 使用缓冲流提高读取性能
byte[] buffer = new byte[8192]; // 使用更大的缓冲区
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.flush();
log.info("文件下载成功,文件大小:{} 字节", ossObject.getObjectMetadata().getContentLength());
} catch (OSSException oe) {
// 针对OSS异常的详细处理
log.error("发生OSS异常,可能是请求被OSS拒绝或其他服务端错误。错误信息:{}, 错误代码:{}, 请求ID:{}, 主机ID:{}", oe.getErrorMessage(), oe.getErrorCode(), oe.getRequestId(), oe.getHostId());
throw new ServiceException("发生OSS异常,可能是请求被OSS拒绝或其他服务端错误");
} catch (Exception e) {
// 针对客户端异常的详细处理
log.error("发生客户端异常,可能是网络问题或内部错误导致与OSS通信失败。错误信息:{}", e.getMessage());
throw new ServiceException("发生客户端异常,可能是网络问题或内部错误导致与OSS通信失败");
} finally {
// 资源清理,确保在 try-with-resources 关闭流之后进行
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}
阿里云文件上传,文件下载工具类(Oss)
于 2024-12-23 13:50:15 首次发布