OSSUtils.java 4.16 KB
package com.subsidy.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.date.DateTime;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class OSSUtils {

    //    @Value("${aliyun.oss.accessKeyId}")
    private static String accessKeyId = "LTAIOrpFKrDqsQ2c";

    //    @Value("${aliyun.oss.accessKeySecret}")
    private static String secretAccessKey = "1Qp8huLETbWiBBJvHXJ7MOIhtKuA1G";

    //    @Value("${aliyun.oss.endpoint}")
    private static String endPoint = "oss-cn-beijing.aliyuncs.com";

    //    @Value("${aliyun.oss.bucketName}")
//    private static String bucketName = "shixischool";
    private static String bucketName = "ykhl-bigger";

    public static String uploadOneFile(String file) throws IOException {

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, secretAccessKey);

        // 设置文件名
        String fileName = new DateTime().toString("yyyy-MM-dd")
                + UUID.randomUUID().toString() + ".jpg";

        // 获取文件后缀名
//        int originalFilenameStartIndex = file.indexOf('/');
//        int originalFilenameEndIndex = file.indexOf(';');
//        String originalFilename = file.substring(originalFilenameStartIndex+1,originalFilenameEndIndex);

        // 获取base64的文件
//        file = file.split(",")[1];

        byte[] bytesFile = Base64.decode(file);
        try {
            // 创建PutObject请求。
            InputStream inputStream = new ByteArrayInputStream(bytesFile);
            ossClient.putObject(bucketName, fileName, inputStream);

            String url = "http://" + bucketName + "." + endPoint + "/" + fileName;
            // System.out.println(url);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }


    public static String image2Base64(String imgUrl) {
        URL url = null;
        InputStream is = null;
        ByteArrayOutputStream outStream = null;
        HttpURLConnection httpUrl = null;

        try {
            url = new URL(imgUrl);
            httpUrl = (HttpURLConnection) url.openConnection();
            httpUrl.connect();
            httpUrl.getInputStream();
            is = httpUrl.getInputStream();
            outStream = new ByteArrayOutputStream();
            // 创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            // 每次读取的字符串长度,如果为-1,代表全部读取完毕
            int len = 0;
            // 使用一个输入流从buffer里把数据读取出来
            while ((len = is.read(buffer)) != -1) {
                // 用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            // 对字节数组Base64编码
            return Base64Util.encode(outStream.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outStream != null) {
                try {
                    outStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpUrl != null) {
                httpUrl.disconnect();
            }
        }
        return imgUrl;
    }

    public static void main(String[] args) {
        System.out.println(image2Base64("https://shixischool.oss-cn-beijing.aliyuncs.com/2022-12-219df5b721-99b7-48c4-916e-e474a4eca946.jpg?x-oss-process=image/auto-orient,1/resize,m_pad,w_500,h_500/quality,Q_100/format,jpg"));
    }
}