oss上传
public class OssHelper {
private static final Logger logger = LoggerFactory.getLogger(OssHelper.class);
private static OssHelper ossHelper = new OssHelper();
private static String domain = "https://bucketName.oss-cn-hangzhou.aliyuncs.com/";
private static String endPoint = "https://oss-cn-hangzhou.aliyuncs.com";
private static String endPointInner = "https://oss-cn-hangzhou-internal.aliyuncs.com";
private String accessKey = "";
private String accessKeySecret = "";
private String bucketName = "bucketName";
private ClientConfiguration clientConfiguration;
static {
if (OSUtils.isLinux()) {
endPoint = endPointInner;
}
}
private OssHelper() {
ClientConfiguration clientConfiguration = new ClientConfiguration();
clientConfiguration.setConnectionTimeout(5000);
clientConfiguration.setSupportCname(true);
clientConfiguration.setRequestTimeout(60000);
clientConfiguration.setSocketTimeout(60000);
this.clientConfiguration = clientConfiguration;
}
public static OssHelper getInstance() {
return ossHelper;
}
public String upload(String prefix, String fileName, InputStream inputStream) {
logger.info("upload file to oss endPoint:{},fileName:{}", endPoint, fileName);
long start = System.currentTimeMillis();
OSSClient ossClient = new OSSClient(endPoint, accessKey, accessKeySecret, clientConfiguration);
fileName = prefix + "/" + fileName;
PutObjectResult result = ossClient.putObject(bucketName, fileName, inputStream);
// 设置文件的访问权限为公共读。
ossClient.setObjectAcl(bucketName, fileName, CannedAccessControlList.PublicRead);
logger.info("upload file to oss result:{},cost {}", result.getETag(), System.currentTimeMillis() - start);
// // 设置URL过期时间为1小时。
// Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000);
// // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
// URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
// logger.info("browser.url:{}", url);
ossClient.shutdown();
return generateSTSUrl(fileName);
}
private String generateSTSUrl(String fileName) {
logger.info("generateSTSUrl fileName:{}", fileName);
String resultUrl = domain + fileName;
logger.info("generateSTSUrl resultUrl:{}", resultUrl);
return resultUrl;
}
}