package com.community.commom.utils;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.net.URL;
import java.util.Date;

/**
 * @author weichaochao
 * @Title: OssUtil
 * @Description: 图片上传到OSS
 * @date 2018/10/31
 */
public class OssUtil {
   /* public static void main(String[] args) {
        // Endpoint以杭州为例，其它Region请按实际情况填写。
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
// 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录 https://ram.console.aliyun.com 创建RAM账号。
        String accessKeyId = "LTAIiG6xeHbVzTXC";
        String accessKeySecret = "YUci8oBtm5WzobH6SP2eyZUbjCBKBo";
        String bucketName = "faceidentity";
// 创建OSSClient实例。
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
// 设置图片处理样式。
        String style = "image/resize,m_fixed,w_100,h_100/rotate,90";
// 指定过期时间为10分钟。
        Date expiration = new Date(System.currentTimeMillis() + 1000 * 60 * 10 );
        GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, "1.png", HttpMethod.GET);
        req.setExpiration(expiration);
        req.setProcess(style);
        URL signedUrl = ossClient.generatePresignedUrl(req);
        System.out.println("url:" + signedUrl);
// 关闭OSSClient。
        ossClient.shutdown();
    }
*/

    public static String picOSS(MultipartFile uploadFile) throws Exception {
        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
        // 云账号AccessKey有所有API访问权限，建议遵循阿里云安全最佳实践，创建并使用RAM子账号进行API访问或日常运维，请登录
        // https://ram.console.aliyun.com 创建
        String accessKeyId = "LTAIiG6xeHbVzTXC";
        String accessKeySecret = "YUci8oBtm5WzobH6SP2eyZUbjCBKBo";
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传
        long time = System.currentTimeMillis();

        ossClient.putObject("bucketName", "filename", new ByteArrayInputStream(uploadFile.getBytes()));
        // 关闭client
        ossClient.shutdown();
        Date expiration = new Date(time + 3600 * 1000 * 24 * 365 * 10);
        String url = ossClient.generatePresignedUrl("bucketName", "filename", expiration).toString();
        return url;
    }
}
