Java获取阿里云图片临时URL与图片文件转换Base64编码方法

本文涉及的产品
对象存储 OSS,20GB 3个月
对象存储 OSS,恶意文件检测 1000次 1年
对象存储 OSS,内容安全 1000次 1年
简介: 在使用阿里云人工智能产品服务时,有部分服务需要上传的参数中包含文件URL,当我们没有开通OSS服务时,可以使用临时URL服务、或部分服务支持Base64编码格式,此文章为生成临时URL-JavaSDK方案与图片文件转换Base64编码方案。

1、临时URL(上海地域)


pom.xml

    <dependency>
         <groupId>com.aliyun</groupId>
            <artifactId>openplatform20191219</artifactId>
            <version>3.0.1</version>
    </dependency>

直接使用即可,通过静态调用


import com.aliyun.fileform.models.FileField;
import com.aliyun.openplatform20191219.models.AuthorizeFileUploadRequest;
import com.aliyun.openplatform20191219.models.AuthorizeFileUploadResponse;
import com.aliyun.oss.models.PostObjectRequest;
import com.aliyun.tea.TeaConverter;
import com.aliyun.tea.TeaPair;
import com.aliyun.teautil.models.RuntimeOptions;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ViapiFileUtilAdvance {
    public static String ViFaceURL(String Url) throws Exception {
        String accessKey = "accessKey";    //您的AccessKeyID
        String accessKeySecret = "accessKeySecret";   //您的AccessKeySecret
        String regionId = "cn-shanghai";
        String file = Url;
        try (InputStream inputStream = buildInputStream(file)) {
            ViapiFileUtilAdvance fileUtils = ViapiFileUtilAdvance.getInstance(accessKey, accessKeySecret, regionId);
            String ossTempFileUrl = fileUtils.upload(inputStream);
            return ossTempFileUrl;
        }
    }

    public static InputStream buildInputStream(String filePath) throws IOException {
        if (StringUtils.startsWithAny(filePath, new CharSequence[]{"http://", "https://"})) {
            filePath = URLDecoder.decode(filePath, "UTF-8");
            URL url = new URL(filePath);
            URLConnection urlConnection = url.openConnection();
            return urlConnection.getInputStream();
        } else {
            File key1 = new File(filePath);
            return new FileInputStream(key1);
        }
    }

    public static synchronized ViapiFileUtilAdvance getInstance(String accessKeyId, String accessKeySecret, String regionId) throws Exception {
        String mapKey = String.format("%s:%s:%s", regionId, accessKeyId, accessKeySecret);
        ViapiFileUtilAdvance fileUtils = _map.get(mapKey);
        if (fileUtils == null) {
            _map.putIfAbsent(mapKey, new ViapiFileUtilAdvance(accessKeyId, accessKeySecret, regionId));
            fileUtils = _map.get(mapKey);
        }
        return fileUtils;
    }


    private ViapiFileUtilAdvance(String accessKeyId, String accessKeySecret, String regionId) throws Exception {
        Map<String, Object> cm = new HashMap<>();
        cm.put("regionId", regionId);
        cm.put("autoretry", "true");
        cm.put("accessKeyId", accessKeyId);
        cm.put("accessKeySecret", accessKeySecret);
        cm.put("connectTimeout", 15 * 1000);
        cm.put("readTimeout", 30 * 1000);
        cm.put("maxIdleConns", 200);
        cm.put("type", "access_key");
        cm.put("endpoint", "openplatform.aliyuncs.com");
        _runtime = RuntimeOptions.build(cm);
        com.aliyun.tearpc.models.Config authConfig = com.aliyun.tearpc.models.Config.build(cm);
        _authClient = new com.aliyun.openplatform20191219.Client(authConfig);
        //ossEndpointType = "internal";//aliyun-vpc
        _ossConfig = com.aliyun.oss.models.Config.build(TeaConverter.buildMap(
                new TeaPair("accessKeySecret", accessKeySecret),
                new TeaPair("type", "access_key"),
                new TeaPair("protocol", _authClient._protocol),
                new TeaPair("regionId", _authClient._regionId)
        ));
    }

    public String upload(InputStream inputStream) throws Exception {
        AuthorizeFileUploadRequest authRequest = AuthorizeFileUploadRequest.build(TeaConverter.buildMap(
                new TeaPair("product", "imageseg"),
                new TeaPair("regionId", _authClient._regionId)
        ));
        AuthorizeFileUploadResponse authResponse = _authClient.authorizeFileUploadWithOptions(authRequest, _runtime);
        com.aliyun.oss.models.Config ossConfig = new com.aliyun.oss.models.Config();
        com.aliyun.openapiutil.Client.convert(_ossConfig, ossConfig);
        ossConfig.accessKeyId = authResponse.accessKeyId;
        ossConfig.endpoint = com.aliyun.openapiutil.Client.getEndpoint(authResponse.endpoint, authResponse.useAccelerate, ossEndpointType);
        com.aliyun.oss.Client ossClient = new com.aliyun.oss.Client(ossConfig);
        FileField fileObj = FileField.build(TeaConverter.buildMap(
                new TeaPair("filename", authResponse.objectKey),
                new TeaPair("content", inputStream),
                new TeaPair("contentType", "")
        ));
        PostObjectRequest.PostObjectRequestHeader ossHeader = PostObjectRequest.PostObjectRequestHeader.build(TeaConverter.buildMap(
                new TeaPair("accessKeyId", authResponse.accessKeyId),
                new TeaPair("policy", authResponse.encodedPolicy),
                new TeaPair("signature", authResponse.signature),
                new TeaPair("key", authResponse.objectKey),
                new TeaPair("file", fileObj),
                new TeaPair("successActionStatus", "201")
        ));
        PostObjectRequest uploadRequest = PostObjectRequest.build(TeaConverter.buildMap(
                new TeaPair("bucketName", authResponse.bucket),
                new TeaPair("header", ossHeader)
        ));
        com.aliyun.ossutil.models.RuntimeOptions ossRuntime = new com.aliyun.ossutil.models.RuntimeOptions();
        com.aliyun.openapiutil.Client.convert(_runtime, ossRuntime);
        ossClient.postObject(uploadRequest, ossRuntime);
        String imageURL = "http://" + authResponse.bucket + "." + authResponse.endpoint + "/" + authResponse.objectKey + "";
        return imageURL;
    }

    RuntimeOptions _runtime;
    com.aliyun.openplatform20191219.Client _authClient;
    com.aliyun.oss.models.Config _ossConfig;
    String ossEndpointType = null;
    static Map<String, ViapiFileUtilAdvance> _map = new ConcurrentHashMap<>();

}

2、Base64编码


直接使用即可,通过静态调用

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public static String encodeImageToBase64(File file) throws Exception {
        //将图片文件转化为字节数组字符串,并对其进行Base64编码处理
        InputStream in = null;
        byte[] data = null;
        //读取图片字节数组
        try {
            in = new FileInputStream(file);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            throw new Exception("图片上传失败!");
        }
        //对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        String base64 = encoder.encode(data);
        return base64;//返回Base64编码过的字节数组字符串
    }
相关实践学习
借助OSS搭建在线教育视频课程分享网站
本教程介绍如何基于云服务器ECS和对象存储OSS,搭建一个在线教育视频课程分享网站。
目录
相关文章
|
1天前
|
安全 Java 机器人
解决Java中的NumberFormatException异常的实用方法
解决Java中的NumberFormatException异常的实用方法
|
23小时前
|
Java 机器人 程序员
Java中的文件I/O操作:流、读写和NIO详解
Java中的文件I/O操作:流、读写和NIO详解
|
23小时前
|
缓存 监控 Java
Java中的内存泄漏及其排查方法
Java中的内存泄漏及其排查方法
|
1天前
|
XML Java 数据格式
java删除xml文件内容
java删除xml文件内容
3 0
|
1天前
|
XML Java 数据格式
java创建xml文件内容
java创建xml文件内容
7 0
|
1天前
|
XML Java 数据格式
java解析xml文件内容
java解析xml文件内容
4 0
|
1天前
|
Java
java反射-动态调用方法(无参无返回值、有参无返回值、有参有返回值)
java反射-动态调用方法(无参无返回值、有参无返回值、有参有返回值)
4 0
|
1天前
|
Java
java反射-获取类的属性、构造方法、方法
java反射-获取类的属性、构造方法、方法
3 0
|
1天前
|
自然语言处理 负载均衡 Java
Java中的微服务架构实现方法*
Java中的微服务架构实现方法*
|
1天前
|
存储 Java 机器人
如何在Java中实现文件压缩与解压?
如何在Java中实现文件压缩与解压?

热门文章

最新文章