【197】JAVA8调用阿里云对象存储API,保存图片并获取图片URL地址。

实际工作中,需要用阿里云对象存储保存图片,并且在上传图片到阿里云对象存储服务器后,获取图片在阿里云对象存储服务器的URL地址,以便给 WEB 前端显示。

阿里云对象存储上传图片的工具类

java 复制代码
package zhangchao;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

/**
 * 阿里云对象存储工具类
 */
public class OSSUtils {
    // OSS阿里云对象存储的AK和SK
    private static final String OSS_AK = "yourAK";
    private static final String OSS_SK = "yourSK";
    // OSS阿里云对象存储的Bucket名称
    private static final String OSS_BUCKET_NAME = "your-files";
    // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
    private static final String OSS_ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";


    /**
     * 上传图片并返回图片URL
     * @return 图片URL
     */
    public static String uploadImage(String imageFilePath) {
        String result = null;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(OSS_ENDPOINT, OSS_AK, OSS_SK);

        FileInputStream fis = null;
        try {
            // 创建存储空间。
            fis = new FileInputStream(imageFilePath);
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            ossClient.putObject(OSS_BUCKET_NAME, uuid, fis);

            // 设置URL过期时间为10年 3600l * 1000 * 24 * 365 * 10
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000L *
                    24L * 365L * 10L);
            URL url = ossClient.generatePresignedUrl(OSS_BUCKET_NAME, uuid, expiration);
            if (url != null) {
                result = url.toString();
            }
        } catch (OSSException oe) {
            StringBuilder sb = new StringBuilder();
            sb.append("Caught an OSSException, which means your request made it to OSS, ")
                    .append("but was rejected with an error response for some reason.");
            sb.append("Error Message:").append(oe.getErrorMessage());
            sb.append("Error Code:").append(oe.getErrorCode());
            sb.append("Request ID:").append(oe.getRequestId());
            sb.append("Host ID:").append(oe.getHostId());
            System.out.println(sb.toString());
        } catch (ClientException ce) {
            StringBuilder sb = new StringBuilder();
            sb.append("Caught an ClientException, which means the client encountered ")
                    .append("a serious internal problem while trying to communicate with OSS, ")
                    .append("such as not being able to access the network.");
            sb.append("Error Message:" + ce.getMessage());
            System.out.println(sb.toString());
            ce.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fis) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return result;
    }
}

调用的 main 方法:

java 复制代码
package zhangchao;

public class Main {
    public static void main(String[] args) {
        String imgUrl = OSSUtils.uploadImage("E:\\ws\\zc\\Java8OSSImg\\src\\main\\resources\\q1.jpg");
        System.out.println(imgUrl);
    }
}

运行结果,这里显示了返回的图片 URL 地址:

bash 复制代码
https://your-files.oss-cn-hangzhou.aliyuncs.com/abc123?Expires=2021599742&OSSAccessKeyId=youAK&Signature=xxxxxx

这个地址没办法用浏览器直接看,需要写个HTML来测试一下。

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <img src="https://your-files.oss-cn-hangzhou.aliyuncs.com/abc123?Expires=2021599742&OSSAccessKeyId=youAK&Signature=xxxxxx">
</body>
</html>
相关推荐
西瓜er27 分钟前
JAVA:Spring Boot 集成 FFmpeg 实现多媒体处理
java·spring boot·ffmpeg
你总是一副不开心的样子(´ . .̫ .31 分钟前
一、十天速通Java面试(第三天)
java·面试·职场和发展·java面试
迎風吹頭髮41 分钟前
UNIX下C语言编程与实践63-UNIX 并发 Socket 编程:非阻塞套接字与轮询模型
java·c语言·unix
我是华为OD~HR~栗栗呀44 分钟前
23届考研-Java面经(华为OD)
java·c++·python·华为od·华为·面试
Javatutouhouduan1 小时前
Java程序员如何深入学习JVM底层原理?
java·jvm·java面试·后端开发·java架构师·java程序员·互联网大厂
王嘉俊9251 小时前
设计模式--享元模式:优化内存使用的轻量级设计
java·设计模式·享元模式
2301_803554522 小时前
C++联合体(Union)详解:与结构体的区别、联系与深度解析
java·c++·算法
EnCi Zheng2 小时前
SpringBoot 配置文件完全指南-从入门到精通
java·spring boot·后端
烙印6012 小时前
Spring容器的心脏:深度解析refresh()方法(上)
java·后端·spring
为什么我不是源代码2 小时前
JPA读取数据库离谱问题-No property ‘selectClassByName‘ found-Not a managed type
java·sql