package com.sifang.modules.alioss;

import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.*;
import com.sifang.modules.sunshine.SystemSetting.utils.StringUtil;
import com.sifang.modules.sys.common.global.Global;
import com.sifang.modules.sys.common.utils.IdGen;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Component;

import javax.imageio.stream.FileImageInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 *
 * @ClassName: AliyunOSSClientUtil
 * @Description: 阿里云OSS上传文件模块
 *
 */
@Component
public class AliyunOSSClientUtil {

//	private final OssBuilder ossBuilder;

   // private static Logger logger = LoggerFactory.getLogger(AliyunOSSClientUtil.class);

    public static long FILE_EXPIRATION_TIME = 1000 * 3600 * 24 * 365 * 10;


	// 阿里云API的内或外网域名
    private static String ENDPOINT;
    // 阿里云API的密钥Access Key ID
    private static String ACCESS_KEY_ID;
    // 阿里云API的密钥Access Key Secret
    private static String ACCESS_KEY_SECRET;
    // 阿里云API的bucket名称
    public static String BACKET_NAME;
    // 阿里云API的文件夹名称
    private static String FOLDER;
    private static String FORMAT;
    private static String FORMATS;
    private static String FOLDER_VIDEO;

    // 初始化属性
    static {
        ENDPOINT = OSSClientConstants.ENDPOINT;
        ACCESS_KEY_ID = OSSClientConstants.ACCESS_KEY_ID;
        ACCESS_KEY_SECRET = OSSClientConstants.ACCESS_KEY_SECRET;
        BACKET_NAME = OSSClientConstants.BACKET_NAME;
        FOLDER = OSSClientConstants.FOLDER;
        FORMAT = OSSClientConstants.FORMAT;
        FORMATS = OSSClientConstants.FORMATS;
        FOLDER_VIDEO = OSSClientConstants.FOLDER_VIDEO;
    }

    /**
     * 获取阿里云OSS客户端对象
     *
     * @return ossClient
     */
    public static OSSClient getOSSClient() {

       // return new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
			OSSClient ossClient = new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
			return ossClient;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(" ossClientFacotry getClient exception!");
        }
    }

    public OSSClient getOSSClient2() {
        try {
		/*	String tenantId = AuthUtil.getTenantId();
			OSSClient ossClient = ossClientMap.get(tenantId);
			if(Func.hasEmpty(ossClient)){
				return ossClient;
			}*/
		//	ossClient =new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

            return new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(" ossClientFacotry getClient exception!");
        }
    }

    /** 上传图片时使用 **/
    /**
     *
     * @param b 文件的二进制流
     * @param extName 文件的扩展名
     * @return 文件存储中数据库的路径
     */
    public static String uploadImage(byte[] b, String extName,String filename) {
        String config = Global.getConfig("s3.enabled");
        if (Objects.equals("false", config) || StringUtils.isBlank(config)) {
            return uploadToAliyunOSS(b, extName, filename);
        } else {
            return S3ClientUtil.uploadImage(b, extName, filename);
        }
    }

    @NotNull
    private static String uploadToAliyunOSS(byte[] b, String extName, String filename) {
        String dateFmt = new SimpleDateFormat("yyyyMMdd").format(new Date());

        if(extName != null && extName.startsWith(".")){
            extName = extName.substring(1);
        }

        String fileName;
        if(StringUtil.isNotBlank(filename) && (filename.startsWith(extName) || filename.endsWith(extName))
                && filename.lastIndexOf(".")>0){
            fileName = filename;
            //文件名后加5位uuid
            String s = UUID.randomUUID().toString().replaceAll("-", "");
            String begin = fileName.substring(0, fileName.lastIndexOf("."));
            begin += "_"+s.substring(s.length()-5);
            fileName = begin+fileName.substring(fileName.lastIndexOf("."));
        }else{
            fileName = IdGen.uuid() +"." + extName;
        }
        String filePath = FOLDER + extName + "/" + dateFmt + "/"+  UUID.randomUUID().toString().replaceAll("-", "") + "/"+ fileName;
        OSSClient ossClient = new AliyunOSSClientUtil().getOSSClient2();

        Long fileSize = (long) b.length;
        // 创建上传Object的Metadata
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(fileSize);
        // 指定该Object被下载时的网页的缓存行为
        metadata.setCacheControl("no-cache");
        // 指定该Object下设置Header
        metadata.setHeader("Pragma", "no-cache");
        // 指定该Object被下载时的内容编码格式
        metadata.setContentEncoding("utf-8");
        // 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
        // 如果没有扩展名则填默认值application/octet-stream
        metadata.setContentType(getContentType("." + extName));
        // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
        metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
        metadata.setObjectAcl(CannedAccessControlList.PublicReadWrite);

        PutObjectResult putResult = ossClient.putObject(BACKET_NAME, filePath, new ByteArrayInputStream(b),
                metadata);
        //ossClientFacotry.releaseConnection(ossClient);
        ossClient.shutdown();
        System.out.println(" >> upload file:" + filePath);
        return filePath;
    }

    /**
     * 创建存储空间
     * !!! 暂时无用 !!!
     *            OSS连接
     * @param bucketName
     *            存储空间
     * @return
     */
    public static String createBucketName(String bucketName) {
        OSSClient ossClient = getOSSClient();
        // 存储空间
        final String bucketNames = bucketName;
        if (!ossClient.doesBucketExist(bucketName)) {
            // 创建存储空间
            Bucket bucket = ossClient.createBucket(bucketName);
            System.out.print("创建存储空间成功");
           // ossClientFacotry.releaseConnection(ossClient);
            return bucket.getName();
        }
        return bucketNames;
    }

    /**
     * 删除存储空间buckName
     * !!! 暂时无用 !!!
     *            oss对象
     * @param bucketName
     *            存储空间
     */
    public static void deleteBucket(String bucketName) {
        OSSClient ossClient = getOSSClient();
        ossClient.deleteBucket(bucketName);
      //  ossClientFacotry.releaseConnection(ossClient);
        System.out.print("删除" + bucketName + "Bucket成功");
    }

    /**
     * 创建模拟文件夹
     * !!! 暂时无用 !!!
     *            oss连接
     * @param bucketName
     *            存储空间
     * @param folder
     *            模拟文件夹名如"qj_nanjing/"
     * @return 文件夹名
     */
    public static String createFolder(String bucketName, String folder) {
        OSSClient ossClient = getOSSClient();
        // 文件夹名
        final String keySuffixWithSlash = folder;
        // 判断文件夹是否存在，不存在则创建
        if (!ossClient.doesObjectExist(bucketName, keySuffixWithSlash)) {
            // 创建文件夹
            ossClient.putObject(bucketName, keySuffixWithSlash, new ByteArrayInputStream(new byte[0]));
            System.out.print("创建文件夹成功");
            // 得到文件夹名
            OSSObject object = ossClient.getObject(bucketName, keySuffixWithSlash);
            String fileDir = object.getKey();
          //  ossClientFacotry.releaseConnection(ossClient);
            return fileDir;
        }
        return keySuffixWithSlash;
    }

    /**
     * 根据key删除OSS服务器上的文件
     * !!! 暂时无用 !!!
     *            oss连接
     * @param bucketName
     *            存储空间
     * @param key
     *            Bucket下的文件的路径名+文件名 如："upload/cake.jpg"
     */
    public static void deleteFile(String bucketName, String key) {
        OSSClient ossClient = getOSSClient();
        ossClient.deleteObject(bucketName, key);
        System.out.print("删除" + bucketName + "下的文件" + key + "成功");
       // ossClientFacotry.releaseConnection(ossClient);
    }



    public static OSSObject downLoadImage(String fileName, String bucketName) {

        OSSClient ossClient =new AliyunOSSClientUtil().getOSSClient2();
        Date expiration = new Date(new Date().getTime() + 3600 * 1000);
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, fileName, HttpMethod.GET);
        // 设置过期时间。
        request.setExpiration(expiration);
        // 生成签名URL（HTTP GET请求）。
        URL signedUrl = ossClient.generatePresignedUrl(request);
        // 使用签名URL发送请求。
        Map<String, String> customHeaders = new HashMap<String, String>();
        // 添加GetObject请求头。
        //customHeaders.put("Range", "bytes=100-1000");
        OSSObject object = ossClient.getObject(signedUrl, customHeaders);
       // ossClient.shutdown();
        return object;
    }

    public static void downLoadFile(String fileName, HttpServletResponse response, String bucketName, HttpServletRequest request) {
        if (StringUtils.isNotBlank(fileName)) {
            OSSObject ossObject = downLoadImage(fileName,bucketName);
            if (ossObject != null) {
                InputStream inputStream = ossObject.getObjectContent();
                int buffer = 1024 * 10;
                byte data[] = new byte[buffer];
                try {
                    //缓冲文件输出流
                    BufferedOutputStream outputStream=new BufferedOutputStream(response.getOutputStream());
                    //通知浏览器以附件形式下载
                    // response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
                    // 为防止 文件名出现乱码
                 //   response.setContentType("application/doc");
                    final String userAgent = request.getHeader("USER-AGENT");
                    if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
                        fileName = URLEncoder.encode(fileName,"UTF-8");
                    }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
                        fileName = new String(fileName.getBytes(), "ISO8859-1");
                    }else{
                        fileName = URLEncoder.encode(fileName,"UTF-8");//其他浏览器
                    }
                    response.setContentType("application/octet-stream");
                    // 文件名可以任意指定
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));//将文件名转为ASCLL编码
                    int read;
                    while ((read = inputStream.read(data)) != -1) {
                       // logger.info("data:{} ",data);
                        outputStream.write(data, 0, read);
                    }
                    if(outputStream!=null){
                        outputStream.flush();
                        outputStream.close();
                    }
                    ossObject.close();
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }



    /**
     * 上传图片至OSS 文件流
     * !!! 暂时无用 !!!
     *            oss连接
     * @param file
     *            上传文件（文件全路径如：D:\\image\\cake.jpg）
     * @param bucketName
     *            存储空间
     *            模拟文件夹名 如"qj_nanjing/"
     * @return String 返回的唯一MD5数字签名
     */
    public static String[] uploadObject2OSS(File file, String bucketName, String user_id) {
        OSSClient ossClient = getOSSClient();
        String resultStr = null;
        String[] fo = new String[] { "", "" };
        try {
            // 以输入流的形式上传文件
            String folder = "";
            folder = FOLDER + user_id + "/" + FORMAT + "/";
            InputStream is = new FileInputStream(file);
            // 文件名
            String timefile = FORMATS;
            String fileName = file.getName();
            fileName = timefile + fileName.substring(fileName.lastIndexOf("."));
            System.out.print("上传到路径" + folder + fileName);
            // 文件大小
            Long fileSize = file.length();
            // 创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            // 上传的文件的长度
            metadata.setContentLength(is.available());
            // 指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("no-cache");
            // 指定该Object下设置Header
            metadata.setHeader("Pragma", "no-cache");
            // 指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            // 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
            // 如果没有扩展名则填默认值application/octet-stream
            metadata.setContentType(getContentType(fileName));
            // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
            metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
            // 上传文件 (上传文件流的形式)
            PutObjectResult putResult = ossClient.putObject(bucketName, folder + fileName, is, metadata);
            // 解析结果
            resultStr = putResult.getETag();
            fo[1] = folder + fileName;
            fo[0] = resultStr;

         //   ossClientFacotry.releaseConnection(ossClient);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("上传阿里云OSS服务器异常." + e.getMessage());
        }
        return fo;
    }

    //!!! 暂时无用 !!!
    //上传路径返回地址，图片视频都可以
    //需要改变上传那文件位置FOLDER
    public static String[] uploadObjectOSS(String file, String bucketName, String user_id) {
        OSSClient ossClient = getOSSClient();
        String resultStr = null;
        String[] fo = new String[] { "", "" };
        try {
            // 以输入流的形式上传文件
            String folder = "";
            folder = FOLDER + user_id + "/" + FORMAT + "/";
//            InputStream is = new FileInputStream(file);
            // 文件名
            String timefile = FORMATS;
//            String fileName = file.getName();
            file = timefile + file.substring(file.lastIndexOf("."));
            System.out.print("上传到路径" + folder + file);
            // 文件大小
            Integer fileSize = file.length();
            // 创建上传Object的Metadata
            ObjectMetadata metadata = new ObjectMetadata();
//            // 上传的文件的长度
//            metadata.setContentLength(is.available());
            // 指定该Object被下载时的网页的缓存行为
            metadata.setCacheControl("no-cache");
            // 指定该Object下设置Header
            metadata.setHeader("Pragma", "no-cache");
            // 指定该Object被下载时的内容编码格式
            metadata.setContentEncoding("utf-8");
            // 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
            // 如果没有扩展名则填默认值application/octet-stream
            metadata.setContentType(getContentType(file));
            // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
            metadata.setContentDisposition("filename/filesize=" + file + "/" + fileSize + "Byte.");
            // 上传文件 (上传文件流的形式)
            PutObjectResult putResult = ossClient.putObject(bucketName, folder + file, new ByteArrayInputStream(file.getBytes("UTF-8")), metadata);
            // 解析结果
            resultStr = putResult.getETag();
            fo[1] = folder + file;
            fo[0] = resultStr;

          //  ossClientFacotry.releaseConnection(ossClient);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.print("上传阿里云OSS服务器异常." + e.getMessage());
        }
        return fo;
    }

    //!!! 暂时无用 !!!
    //上传视频
    public static String uploadByteVideoOSS(byte[] b, String bucketName, String user_id) {
        OSSClient ossClient = getOSSClient();
        // byte[] content = "Hello OSS".getBytes();

        // 以输入流的形式上传文件
        String folder = "";
        folder = FOLDER_VIDEO + user_id + "/" + FORMAT + "/";
        // 文件名
        String timefile = FORMATS;// 文件名
        String fileName = ".MP4";// 后缀扩展名
        fileName = timefile + fileName;
        System.out.print("上传到路径" + folder + fileName);

        Long fileSize = (long) b.length;

        // 创建上传Object的Metadata
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(fileSize);
        // 指定该Object被下载时的网页的缓存行为
        metadata.setCacheControl("no-cache");
        // 指定该Object下设置Header
        metadata.setHeader("Pragma", "no-cache");
        // 指定该Object被下载时的内容编码格式
        metadata.setContentEncoding("utf-8");
        // 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
        // 如果没有扩展名则填默认值application/octet-stream
        metadata.setContentType(getContentType(fileName));
        // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
        metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");

        PutObjectResult putResult = ossClient.putObject(bucketName, folder + fileName, new ByteArrayInputStream(b),
                metadata);
      //  ossClientFacotry.releaseConnection(ossClient);
        String filepath = folder + fileName;
        return filepath;
    }

    //!!! 暂时无用 !!!
    //上传图片
    public static String uploadByteOSS(byte[] b, String bucketName, String user_id) {
        OSSClient ossClient = getOSSClient();
        // byte[] content = "Hello OSS".getBytes();

        // 以输入流的形式上传文件
        String folder = "";
        folder = FOLDER + user_id + "/" + FORMAT + "/";
        // 文件名
        String timefile = FORMATS;// 文件名
        String fileName = ".jpg";// 后缀扩展名
        fileName = timefile + fileName;
        System.out.print("上传到路径" + folder + fileName);

        Long fileSize = (long) b.length;
//        String timefile = FORMATS;
////        String fileName = file.getName();
//        file = timefile + file.substring(file.lastIndexOf("."));
        // 创建上传Object的Metadata
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(fileSize);
        // 指定该Object被下载时的网页的缓存行为
        metadata.setCacheControl("no-cache");
        // 指定该Object下设置Header
        metadata.setHeader("Pragma", "no-cache");
        // 指定该Object被下载时的内容编码格式
        metadata.setContentEncoding("utf-8");
        // 文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
        // 如果没有扩展名则填默认值application/octet-stream
        metadata.setContentType(getContentType(fileName));
        // 指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
        metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");

        PutObjectResult putResult = ossClient.putObject(bucketName, folder + fileName, new ByteArrayInputStream(b),
                metadata);
       // ossClientFacotry.releaseConnection(ossClient);
        String filepath = folder + fileName;
        return filepath;
    }

    public static byte[] image2Bytes(String imgSrc) throws Exception {
        FileInputStream fin = new FileInputStream(new File(imgSrc));
        // 可能溢出,简单起见就不考虑太多,如果太大就要另外想办法，比如一次传入固定长度byte[]
        byte[] bytes = new byte[fin.available()];
        // 将文件内容写入字节数组，提供测试的case
        fin.read(bytes);

        fin.close();
        return bytes;
    }

    //!!! 暂时无用 !!!
    //图片转化为byte数组
    public static byte[] image2byte(String path) {
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        } catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return data;
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName
     *            文件名
     * @return 文件的contentType
     */
    public static String getContentType(String fileName) {
        // 文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".pdf".equalsIgnoreCase(fileExtension)) {
            return "application/pdf";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension)
                || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || ".pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || ".docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xls".equalsIgnoreCase(fileExtension)) {
            return "application/x-xls";
        }
        if (".xlsx".equalsIgnoreCase(fileExtension)) {
            return "application/octet-stream";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        if (".mp4".equalsIgnoreCase(fileExtension)) {
            return "video/mp4";
        }
        if (".dwg".equalsIgnoreCase(fileExtension)) {
            return "image/vnd.dwg";
        }

        // 默认返回类型
        return "image/jpeg";
    }

    /**
     * 获得url链接
     *
     * @return
     */
    public static String getUrl(String bucketName, String fileName) {
        if(StringUtil.isBlank(bucketName)){
            bucketName = BACKET_NAME;
        }
        OSSClient ossClient = getOSSClient();
        // 设置URL过期时间为 3600* 1000  //*24*365*10
        Date expiration = new Date(new Date().getTime() + AliyunOSSClientUtil.FILE_EXPIRATION_TIME);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, fileName, expiration);
      //  ossClientFacotry.releaseConnection(ossClient);
        if (url != null) {
            return url.toString();
        }
        return "获网址路径出错";
    }

    public static Set<String> getFileUrlList(String fileNmae){

        Set<String> set = new HashSet<>();
        String[] file = fileNmae.split(",");
        for (String filename : file) {
           String url = AliyunOSSClientUtil.getUrl(BACKET_NAME, filename);
            set.add(url);
        }
        return set;
    }


    public String urlpath(String user_id, String files) {
        String[] file = files.split(",");
        String url = "";
        for (String filename : file) {
            // System.out.println("filename:"+filename);
            File filess = new File(filename);
            String[] s = AliyunOSSClientUtil.uploadObject2OSS(filess, BACKET_NAME, user_id);
            System.out.print("上传后的文件MD5数字唯一签名:" + s[0]);
            System.out.print("文件路径:" + s[1]);
            url = AliyunOSSClientUtil.getUrl(BACKET_NAME, s[1]);
            System.out.print("访问网址路径:" + url);
        }
        // 上传后的文件MD5数字唯一签名:40F4131427068E08451D37F02021473A
        return url;
    }

    public String uploadvideo(String url){
        String user_id="localism";
        String[] urllist= AliyunOSSClientUtil.uploadObject2OSS(new File(url), BACKET_NAME, user_id);
        String c=urllist[1];
        return c;
    }

    // urlPath 文件url 地址
   public static byte[] getFileBytes(String urlPath) throws IOException {
       URL url=new URL(urlPath);
       HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
       connection.connect();
       InputStream cin=connection.getInputStream();
       ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
       byte[] buffer=new byte[1024];
       int len=0;
       while ((len=cin.read(buffer))!=-1){
           outputStream.write(buffer, 0, len);
       }
       cin.close();
       byte[] fileData= outputStream.toByteArray();
       outputStream.close();
       return fileData;
   }

   //根据文件的url 将文件保存我们服务器
    public static String saveUrlWeb(String urlPath) throws IOException {
        byte[] fileData=getFileBytes(urlPath);
        String fileInfo= AliyunOSSClientUtil.uploadImage(fileData, "pdf","");
        return fileInfo;
    }

    public static String saveUrlWeb(String urlPath,String extName) throws IOException {
        byte[] fileData=getFileBytes(urlPath);
        String fileInfo= AliyunOSSClientUtil.uploadImage(fileData, extName,"");
        return fileInfo;
    }


}
