package com.community.huiju.service.impl;

import com.aliyun.oss.OSSClient;
import com.community.huiju.service.ImageServiceI;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;

/**
 * @author weichaochao
 * @Title: ImageServiceimpl
 * @Description: 获取图片地址实现类
 * @date 2018/11/5
 */
@Service("ImageService")
public class ImageServiceimpl implements ImageServiceI {

    private static String endpoint = "http://oss-cn-shanghai.aliyuncs.com";
    private static String accessKeyId = "LTAIkc75dpkJw8Lb";
    private static String accessKeySecret = "v4bvXCaix6vSDTCFfwSAdqV53iFEQw";
    private static String bucketName = "jingcheng-h5temp";

    @Override
    public String getImageUrl(MultipartFile uploadFile) throws IOException {

        String imgName = System.currentTimeMillis() + ".png";
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        // 上传
        long time = System.currentTimeMillis();

        ossClient.putObject(bucketName, imgName, new ByteArrayInputStream(uploadFile.getBytes()));

        // 关闭client
        ossClient.shutdown();
        Date expiration = new Date(time + 3600 * 1000 * 24 * 365 * 10);
        String url = ossClient.generatePresignedUrl(bucketName, imgName, expiration).toString();

        // 截取掉签名
        url = url.substring(0, url.lastIndexOf("&Signature"));
        return url;
    }
}
