一、配置mavan依赖
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.11.3</version>
</dependency>
二、Java代码
2.1 OssComponent
@Slf4j
@Component
public class OssComponent {
@Resource
private OssConfig ossConfig;
@Value("${spring.profiles.active}")
private String active;
public String uploadByInputStream(InputStream inputStream,
Long memberId, String fileName) {
String bucketName = getBucketName();
// /content/{memberId}/{datetime.now.date}/xxxxxxx.jpg
String date = DateFormatUtils.format(new Date(), "yyyy-MM-dd");
String objectName = StrUtil.format("content/{}/{}/{}", memberId, date, fileName);
OSS ossClient = new OSSClientBuilder().build(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
try {
PutObjectResult result = ossClient.putObject(bucketName, objectName, inputStream);
if (StringUtil.isNotEmpty(result.getETag())) {
String newUrl = StrUtil.format("https://{}.{}/{}",bucketName,ossConfig.getEndpoint(),objectName);
return newUrl;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return null;
}
private String getBucketName() {
if ("prod".equals(active)) {
return "prod-public";
} else {
return "test-public";
}
}
}
2.2 OssConfig
@Data
@Component
@ConfigurationProperties(prefix="aliyun-oss")
public class OssConfig {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String roleArn;
private Long durationSeconds;
private String bucketName;
}
2.3 loadImage
/**
* 上传图片到OSS
*
* @param originUrl:可访问的待上传图片的全地址
* @param memberId
* @return 上传到OSS的新地址
*/
private String loadImage(String originUrl, Long memberId) {
try {
String[] fileNameArray = originUrl.split("/");
String fileName = fileNameArray[fileNameArray.length - 1];
if (fileName.contains("?")) {
fileName = fileName.split("\\?")[0];
}
byte[] byteArray = Jsoup.connect(originUrl).validateTLSCertificates(false).ignoreContentType(true).maxBodySize(Integer.MAX_VALUE).execute().bodyAsBytes();
InputStream inputStream = new ByteArrayInputStream(byteArray);
return ossComponent.uploadByInputStream(inputStream, memberId, fileName);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
网友评论