springboot oss上传base64图片及其url解密

package com.sl.zs.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;


/**
 * @description:oss 上传图片
 * @author: hxy
 * @date: Created in 2020/8/14 10:46
 * @version: 1.0.0
 * @modified By:
 */
@Component
public class OssUtils {
    @Value("${oss.endpoint}")
    private String endpoint;
    @Value("${oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${oss.accessKeyId}")
    private String accessKeyId;
    @Value("${oss.bucketName}")
    private String bucketName;
    @Value("${oss.imgUrl}")
    private String imgUrl;
    @Value("${oss.packAge}")
    private String packAge;

    /**
     * 基础获取URL的过期时间 : 10分钟
     */
    final static Long EXPIRESTIME = 1000 * 60 * 10L;

    /**
     * 上传base64的图片到阿里云
     * @param base64 baseUrl
     */
    public String uploadImg(String base64) {
        String fileName= OssUtils.generateRandomFilename()+".jpeg";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String name=packAge+"/"+dateFormat.format(new Date())+"/"+fileName;
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
        // 上传Byte数组。
        byte[] imageBase64ToByteArray = ImageUtils.imageBase64ToByteArray(base64, 300*1024);
        ossClient.putObject(bucketName, name, new ByteArrayInputStream(imageBase64ToByteArray));
        System.out.println("上传图片至阿里云:"+bucketName + "/"+ name);
        // 关闭OSSClient。
        ossClient.shutdown();
        return fileName;
    }

    /**
     * 上传文件到阿里云
     * @param str 字符串
     * @param name 文件名字
     */
    public void upload(String str,String name) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);

        ossClient.putObject(bucketName, name,new ByteArrayInputStream(str.getBytes()));
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * 上传流文件
     * @param inputStream
     * @param name
     */
    public void upload(InputStream inputStream,String name) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
        ossClient.putObject(bucketName, name,inputStream);
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * 上传PDF文件
     * @param inputStream
     * @param name
     * @param fileName
     */
    public void uploadPdf(InputStream inputStream,String name,String fileName) {
        // 创建OSSClient实例。
        // 创建上传Object的Metadata
        ObjectMetadata meta = new ObjectMetadata();
        meta.setContentDisposition("attachment;filename="+fileName+".pdf");
        // 设置上传文件长度
//		meta.setContentLength(content.length());
        // 设置上传MD5校验
//		String md5 = BinaryUtil.toBase64String(BinaryUtil.calculateMd5(content.getBytes()));
//		meta.setContentMD5(md5);
        // 设置上传内容类型
//		meta.setContentType("text/plain");
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
        ossClient.putObject(bucketName, name,inputStream,meta);
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    /**
     * 获取文件请求路径
     * @param ObjectName 文件名
     * @return
     */
    public String getUrl(String ObjectName) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
        // 设置URL过期时间为1小时。
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 60);
        // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, ObjectName, expiration);
        // 关闭OSSClient。
        ossClient.shutdown();
        return imgUrl+url.getFile();
    }

    /**
     *
     * @param ObjectName
     * @param second 过期时间秒
     * @return
     */
    public String getUrl(String ObjectName,long second) {
        // 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId,accessKeySecret);
        // 设置URL过期时间为1小时。
        Date expiration = new Date(System.currentTimeMillis() + second);
        // 生成以GET方法访问的签名URL,访客可以直接通过浏览器访问相关内容。
        URL url = ossClient.generatePresignedUrl(bucketName, ObjectName, expiration);
        // 关闭OSSClient。
        ossClient.shutdown();
        return imgUrl+url.getFile();
    }

    /**
     * 读取阿里云oss上的照片为base64
     * @param imagesUrl 图片名称
     * @return
     */
    public String getImage2Base64(String imagesUrl) {
        if (StringUtils.isBlank(imagesUrl)) {
            //throw new CheckException("图片地址为空");
        }
        //ContextLog.printSeparator("imagesUrl:" + imagesUrl);
        // 指定过期时间为十分钟。
        Date expiration = new Date(System.currentTimeMillis() + EXPIRESTIME);

        OSS ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

        URL signedUrl = ossClient.generatePresignedUrl(bucketName, imagesUrl, expiration);

        //2,得到HttpClient对象
        CloseableHttpClient client = HttpClients.createDefault();//获取DefaultHttpClient请求  使用的仍然是HttpClientBuilder.create().build();
        //3,设置请求方式
        HttpGet get = new HttpGet(signedUrl.toString());
        //4,执行请求, 获取响应信息
        CloseableHttpResponse response = null;
        try {
            response = client.execute(get);
            if(200 != response.getStatusLine().getStatusCode()){
                //System.out.println("获取阿里云人像照片失败:code:" + response.getStatusLine().getStatusCode());
                //ContextLog.info("获取阿里云人像照片失败:code:", response.getStatusLine().getStatusCode(), "com.csi.modules.sdk.aliyun.OSSUtils.getImage2Base64", OSSUtils.class);
            }
            //得到实体
            HttpEntity entity = response.getEntity();
            byte[] data = EntityUtils.toByteArray(entity);
            //返回Base64编码过的字节数组字符串,无前缀标识,如需要可手动添加“data:image/jpeg;base64,”
            return Base64.encodeBase64String(data);
        } catch (IOException e) {
            //ContextLog.error("获取阿里云人像照片转换异常:", e);
        }finally {
            try {
                if (response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }


    /**
     * @description 生成随机文件名,防止上传文件后文件名重复
     * @author hxy
     * @date 2020/8/14 12:08
     * @return
     */
    public static String generateRandomFilename(){
        String RandomFilename = "";
        //生成随机数
        Random rand = new Random();
        int random = rand.nextInt();

        Calendar calCurrent = Calendar.getInstance();
        int intDay = calCurrent.get(Calendar.DATE);
        int intMonth = calCurrent.get(Calendar.MONTH) + 1;
        int intYear = calCurrent.get(Calendar.YEAR);
        String now = String.valueOf(intYear) + "_" + String.valueOf(intMonth) + "_" +
                String.valueOf(intDay) + "_";

        RandomFilename = now + String.valueOf(random > 0 ? random : ( -1) * random);

        return RandomFilename;
    }
}



package com.init.webSocket.utils;

import org.apache.commons.codec.binary.Base64;

/**
 * @description: 图片上传限制大小
 * @author: hxy
 * @date: Created in 2020/8/14 10:46
 * @version: 1.0.0
 * @modified By:
 */
public class ImageUtils {

    public static byte[] imageBase64ToByteArray(String base64Str,int size) {
         //判断是否包含前缀,去掉前缀
        if (base64Str.contains(",")) {
            base64Str = base64Str.split(",")[1];
        }
        byte[] decodeFromString = Base64.decodeBase64(base64Str);
        if (decodeFromString.length / 1024 > size) {
            log.error("base64图片超出大小限制,base64:" +" 限制大小:"+size);
        }
        return decodeFromString;
    }
}

//实时照片  base64及其url UTF解码上传至OSS
    try {
         String dataDecoded = java.net.URLDecoder.decode(faceInfoLog.getPhoto(), "utf-8");
         System.out.println(OSSUtil.getUrl(OSSUtil.uploadImg(dataDecoded)));
    } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
    }
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值