美文网首页
Jsoup工具类上传图片到OSS

Jsoup工具类上传图片到OSS

作者: AC编程 | 来源:发表于2022-10-20 10:10 被阅读0次

一、配置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;
    }

相关文章

网友评论

      本文标题:Jsoup工具类上传图片到OSS

      本文链接:https://www.haomeiwen.com/subject/lafuzrtx.html