OSSClientUtil工具类

作者: 奇点一氪 | 来源:发表于2019-12-04 17:43 被阅读0次

阿里的oss工具类


package co.chexiao.lucky.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import co.chexiao.lucky.util.HttpUtil;

public class OSSClientUtil {
    private static Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);
    private static String CONTENT_TYPE_IMAGE = "image/jpeg";
    private static String CONTENT_TYPE_TXT = "text/xml";
    private static String CONTENT_TYPE_PDF = "application/pdf";
    private static String CONTENT_TYPE_EXECL = "application/vnd.ms-excel";
    private static OSSClient ossClient;
    private static OSSClient ossClientUrl;
    private static String bucketName = co.chexiao.lucky.util.PropertiesUtil.getValueByKey("oss.bucketName");
    
    static {
        ossClient = new OSSClient(PropertiesUtil.getValueByKey("oss.endpoint"),
                                                    PropertiesUtil.getValueByKey("oss.accessKeyId"),
                                                    PropertiesUtil.getValueByKey("oss.accessKeySecret"));
        ossClientUrl = new OSSClient(PropertiesUtil.getValueByKey("oss.endpoint.url"),
                PropertiesUtil.getValueByKey("oss.accessKeyId"),
                PropertiesUtil.getValueByKey("oss.accessKeySecret"));
    }
    
    
    
    private static OSSClient getOssClient() {
        return ossClient;
    }

    private static String getBucketName() {
        return bucketName;
    }

    private static void setOssClient(OSSClient ossClient) {
        OSSClientUtil.ossClient = ossClient;
    }

    private static void setBucketName(String bucketName) {
        OSSClientUtil.bucketName = bucketName;
    }

    public static OSSClient getOssClientUrl() {
        return ossClientUrl;
    }

    public static void setOssClientUrl(OSSClient ossClientUrl) {
        OSSClientUtil.ossClientUrl = ossClientUrl;
    }

    /**
     * 上传文件至阿里云
     * @param imgBase64Content:待上传图片Base64字符串内容
     * @param key: 阿里云文件名
     * @return
     * @throws IOException
     */
    public static String uploadBase64Img2OSS(String imgBase64Content, String key) {
        InputStream in = null;
        try {
            if (imgBase64Content != null) {
    
                BASE64Decoder decoder = new BASE64Decoder();
                imgBase64Content = imgBase64Content.replace("data:image/jpeg;base64,", "");
                imgBase64Content = imgBase64Content.replace(" ", "+").replace("\r\n", "");
                byte[] content = decoder.decodeBuffer(imgBase64Content);
                for (int i = 0; i < content.length; ++i) {
                    if (content[i] < 0) {// 调整异常数据
                        content[i] += 256;
                    }
                }
                in = new ByteArrayInputStream(content);
                return uploadFile2OSS(key, in, CONTENT_TYPE_IMAGE);
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error("uploadImg2OSS failed:" + e.getMessage());
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception ex) {

                }
            }
        }
    }
    
    /**
     * 上传文件至阿里云
     * @param pdfBase64Content:待上传图片Base64字符串内容
     * @param key: 阿里云文件名
     * @return
     * @throws IOException
     */
    public static String uploadBase64Pdf2OSS(String pdfBase64Content, String key) {
        InputStream in = null;
        try {
            if (pdfBase64Content != null) {
    
                BASE64Decoder decoder = new BASE64Decoder();
                pdfBase64Content = pdfBase64Content.replace("data:application/pdf;base64,", "");
                pdfBase64Content = pdfBase64Content.replace(" ", "+").replace("\r\n", "");
                byte[] content = decoder.decodeBuffer(pdfBase64Content);
                for (int i = 0; i < content.length; ++i) {
                    if (content[i] < 0) {// 调整异常数据
                        content[i] += 256;
                    }
                }
                in = new ByteArrayInputStream(content);
                return uploadFile2OSS(key, in, CONTENT_TYPE_PDF);
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error("uploadImg2OSS failed:" + e.getMessage());
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception ex) {

                }
            }
        }
    }
    
    /**
     * fileType有以下取值
     *  1: excel
     *  2: txt
     *  3: csv
     *  4: pdf
     *  5:jpeg
     * @param content
     * @param key
     * @param fileType
     * @return
     */
    public static String uploadBase64Content2OSS(String content, String key, int fileType) {
        InputStream in = null;
        try {
            if (content != null) {
                String fileContentPrefix = null;
                if (content.startsWith("data")) {
                    int index = content.indexOf(",");
                    fileContentPrefix = content.substring(0, index);
                    content = content.substring(index+1,content.length());
                }
                Map<String, String> suffixMap = determineFileSuffix(fileContentPrefix, fileType);
                BASE64Decoder decoder = new BASE64Decoder();
                content = content.replace(" ", "+").replace("\r\n", "");
                byte[] contentBytes = decoder.decodeBuffer(content);
                for (int i = 0; i < contentBytes.length; ++i) {
                    if (contentBytes[i] < 0) {// 调整异常数据
                        contentBytes[i] += 256;
                    }
                }
                in = new ByteArrayInputStream(contentBytes);
                return uploadFile2OSS(key+suffixMap.get("suffix"), in, suffixMap.get("contentType"));
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error("uploadImg2OSS failed:" + e.getMessage());
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception ex) {

                }
            }
        }
    
    }
    
    /**
     * 将微信文件上传至阿里云OSS
     * @param serverId:网络文件URL
     * @param key:文件名
     * @return
     */
    public static String uploadWXContent2OSS(String serverId, String key, String wxAccessToken, String contentType){
        InputStream inputStream = null;
        try {
            String urlString = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
                    + wxAccessToken
                    + "&media_id="
                    + serverId;
            
            return uploadURLContent2OSS(urlString, key, contentType);
        } catch (Exception e) {
            logger.error("uploadImg2OSS failed:" + e.getMessage());
            e.printStackTrace();
        }finally{
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception ex) {

                }
            }
        }
        return null;
    }
    
    
    /**
     * 上传文件至阿里云
     * @param xmlContent:待上传图片Base64字符串内容
     * @param key: 阿里云文件名
     * @return
     * @throws IOException
     */
    public static String uploadXML2OSS(String xmlContent, String key) {
        InputStream in = null;
        InputStream output = null;
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        byte[] data = null;
        try {
            if (StringUtils.isNotBlank(xmlContent)) {
                    in = new ByteArrayInputStream(xmlContent.getBytes("UTF-8"));
                    /** 
                     * 根据实际运行效果 设置缓冲区大小 
                     */  
                    byte[] buffer=new byte[1024 * 100];  
                    int ch = 0;  
                    while ((ch = in.read(buffer)) != -1) {  
                        bytesOut.write(buffer,0,ch);  
                    }  
                     
                    data = bytesOut.toByteArray();
                    output = new ByteArrayInputStream(data);
                    return uploadFile2OSS(key, output, CONTENT_TYPE_TXT);
            } else {
                return null;
            }
        } catch (Exception e) {
            logger.error("uploadXML2OSS failed:" + e.getMessage());
            return null;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (Exception ex) {

                }
            }
            
            if (output != null) {
                try {
                    output.close();
                } catch (Exception ex) {

                }
            }
            
            if (bytesOut != null) {
                try {
                    bytesOut.close();
                } catch (Exception ex) {

                }
            }
        }
    }

    /**
     *  上传分片文件至阿里云
     * @param file
     * @param key
     * @return
     * @throws IOException
     */
    public static String uploadImg2OSS(MultipartFile file, String key){
        String urlString = null;
        try {
            urlString = uploadFile2OSS(key,file.getInputStream(), CONTENT_TYPE_IMAGE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return urlString;
    }
    
    /**
     * 上传本地文件到阿里云OSS中
     * @param filePath:本地文件完整文件名(含路径)
     * @return
     */
    public static String uploadLocalImg2OSS(String filePath, String key) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(filePath);
            String uploadImg2OSS = uploadFile2OSS(key, inputStream, CONTENT_TYPE_IMAGE);
            return uploadImg2OSS;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception ex) {

                }
            }
        }
    }
    
    /**
     * 将网络流文件上传至阿里云OSS
     * @param url:网络文件URL
     * @param key:文件名
     * @return
     */
    public static String uploadURLImg2OSS(String url, String key){
        InputStream inputStream = null;
        InputStream output = null;
        try {
            byte[] content = HttpUtil.downloadFile(url);
            if(content == null)
                return null;
            
            output = new ByteArrayInputStream(content);
            return uploadFile2OSS(key, output, CONTENT_TYPE_IMAGE);
        } catch (Exception e) {
            logger.error("uploadImg2OSS failed:" + e.getMessage());
            e.printStackTrace();
        }finally{
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception ex) {

                }
            }
            
            if (output != null) {
                try {
                    output.close();
                } catch (Exception ex) {

                }
            }
        }
        return null;
    }
    
    public static String uploadURLContent2OSS(String url, String key, String contentType){
        InputStream inputStream = null;
        InputStream output = null;
        try {
            byte[] content = HttpUtil.downloadFile(url);
            if(content == null)
                return null;
            
            output = new ByteArrayInputStream(content);
            return uploadFile2OSS(key, output, contentType);
        } catch (Exception e) {
            logger.error("uploadImg2OSS failed:" + e.getMessage());
            e.printStackTrace();
        }finally{
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception ex) {

                }
            }
            
            if (output != null) {
                try {
                    output.close();
                } catch (Exception ex) {

                }
            }
        }
        return null;
    }
    
    
    /**
     * 将微信文件上传至阿里云OSS
     * @param serverId:网络文件URL
     * @param key:文件名
     * @return
     */
    public static String uploadWXImg2OSS(String serverId, String key, String wxAccessToken){
        InputStream inputStream = null;
        try {
            String urlString = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="
                    + wxAccessToken
                    + "&media_id="
                    + serverId;
            
            return uploadURLImg2OSS(urlString, key);
        } catch (Exception e) {
            logger.error("uploadImg2OSS failed:" + e.getMessage());
            e.printStackTrace();
        }finally{
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception ex) {

                }
            }
        }
        return null;
    }
    
    /**
     * @Title: uploadLocalExecl2OSS
     * @Description: 上传本地excel文件到阿里云OSS中
     * @param filePath 文件的路径
     * @param key 文件名称
     * @return String excel文件访问地址
     * @throws
     */
    public static String uploadLocalExecl2OSS(String filePath, String key) {
        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream(filePath);
            String urlString = uploadFile2OSS(key, inputStream, CONTENT_TYPE_EXECL);
            
            logger.info("method[uploadLocalExecl2OSS] return url is: " + urlString);
            return urlString;
        } catch (Exception e) {
            logger.error("method[uploadLocalExecl2OSS] ,异常为:" + e);
            e.printStackTrace();
            return null;
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {}
            }
        }
    }
    
    
    /*****
     * 将文件上传到阿里云
     * @param key:阿里文件名
     * @param in:文件输入流
     * @return  阿里云访问URL
     */
    private static String uploadFile2OSS(String key, InputStream in, String contentType){
        ObjectMetadata objectMetadata = new ObjectMetadata();
        try {
            objectMetadata.setContentLength(in.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(contentType);
            
            ossClient.putObject(bucketName, key, in, objectMetadata);
        
            String urlString = getAccessURL(key);
            
            logger.info("method[uploadFile2OSS] return url is: " + urlString + ", and key is: " + key);
            return urlString;
        } catch (Exception e) {
            logger.error("alioss put object failed:" + e);
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    
    /****
     * 
     * @param key
     * @return
     */
    public static String getAccessURL(String key){
        Date expiration = new Date(new Date().getTime() + 3600 * 1000 * 24 * 365 * 100);    //100年
        URL url = ossClientUrl.generatePresignedUrl(bucketName, key, expiration);
        String urlString = url.toString();
        urlString = urlString.substring(0,urlString.indexOf("?"));//截取?之前的内容,减少空间占用
        logger.info("url: "+urlString);
        return urlString;
    }
    
    /**
       * Description: 判断OSS服务文件上传时文件的contentType
       *
       * @param FilenameExtension 文件后缀
       * @return String
       */
      public static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase("bmp")) {
          return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase("gif")) {
          return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase("jpeg") ||
            FilenameExtension.equalsIgnoreCase("jpg") ||
            FilenameExtension.equalsIgnoreCase("png")) {
          return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase("html")) {
          return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase("txt")) {
          return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase("vsd")) {
          return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase("pptx") ||
            FilenameExtension.equalsIgnoreCase("ppt")) {
          return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase("docx") ||
            FilenameExtension.equalsIgnoreCase("doc")) {
          return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase("xml")) {
          return "text/xml";
        }
        return "image/jpeg";
      }
    
      /**
       * 解析base64编码的文件,获取文件后缀名和contentType
       * @param fileContentPrefix
       * @param fileType
       * @return
       */
      public static Map<String,String> determineFileSuffix(String fileContentPrefix,Integer fileType) {
          Map<String, String> map = new HashMap<String, String>();
          if (fileType == 1) {//excel
              map.put("contentType", "application/vnd.ms-excel");
              if (fileContentPrefix != null && fileContentPrefix.contains("vnd.ms-excel")) {
                  map.put("suffix", ".xls");
              }else {
                  map.put("suffix", ".xlsx");
              }
          } else if (fileType == 2) {//txt
              map.put("contentType",  "text/plain");
              map.put("suffix", ".txt");
          } else if (fileType == 3) {//csv
              map.put("contentType",  "application/vnd.ms-excel");
              map.put("suffix", ".csv");
          } else if (fileType == 4) {//pdf
              map.put("contentType",  "application/pdf");
              map.put("suffix", ".pdf");
          } else if (fileType == 5) {//image
              map.put("contentType",  "image/jpeg");
              if (fileContentPrefix != null) {
                  if (fileContentPrefix.contains("jpeg")) {
                      map.put("suffix", ".jpg");
                  } else if (fileContentPrefix.contains("png")) {
                      map.put("suffix", ".png");
                  } else if (fileContentPrefix.contains("gif")) {
                      map.put("suffix", ".gif");
                  } else if (fileContentPrefix.contains("bmp")) {
                      map.put("suffix", ".bmp");
                  }
              } else {
                  map.put("suffix", ".jpg");
              }
          } else if (fileType == 6) {
              map.put("contentType", "application/vnd.ms-excel");
              map.put("suffix", ".xls");
          }
          else {
              map.put("contentType",  "image/jpeg");
              map.put("suffix", ".jpg");
          }
          return map;
      }
      
      public static Map<String,String> determineFileSuffixByFileType(Integer fileType) {
          Map<String, String> map = new HashMap<String, String>();
          if (fileType == 1) {//excel
              map.put("contentType", "application/vnd.ms-excel");
              map.put("suffix", ".xls");
          } else if (fileType == 2) {//txt
              map.put("contentType",  "text/plain");
              map.put("suffix", ".txt");
          } else if (fileType == 3) {//csv
              map.put("contentType",  "application/vnd.ms-excel");
              map.put("suffix", ".csv");
          } else if (fileType == 4) {//pdf
              map.put("contentType",  "application/pdf");
              map.put("suffix", ".pdf");
          } else if (fileType == 5) {//image
              map.put("contentType",  "image/jpeg");
              map.put("suffix", ".jpg");
          }else {
              map.put("contentType",  "image/jpeg");
              map.put("suffix", ".jpg");
          }
          return map;
      }
      /****
       * 
       * @param argc
       */
    public static void main(String argc[]){
        String endPoint = "http://oss-cn-beijing.aliyuncs.com/";
        String accessKeyId = "LTAIK9ll0KNxPuDa";
        String accessSecret = "ALESaVe9ldDffrjHS1e3eXtlu0owFg";
        String bucketName = "sunshinetest";
//      String fileURL = "http://n.sinaimg.cn/news/transform/20170823/In0W-fykcypq4080200.jpg";
        
//      String strContent = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><简历信息><简历完整度>70</简历完整度><邮件地址>125323338@qq.com</邮件地址><电话号码>18505013700</电话号码><二度好友数量>0</二度好友数量><一度好友数量>0</一度好友数量><关注猎头数>0</关注猎头数><行业编码>500</行业编码><行业名称>信托/担保/拍卖/典当</行业名称><薪资>20000</薪资><薪资月数>12</薪资月数><工作年限>6</工作年限><工作地点名称>福州</工作地点名称><工作地点编码>090020</工作地点编码><学历信息><毕业时间>201707</毕业时间><学历编码>40</学历编码><学历名称>本科</学历名称><入学时间>201207</入学时间><是否统招>0</是否统招><学校名称>西安交通</学校名称></学历信息><学历信息><毕业时间>201207</毕业时间><学历编码>50</学历编码><学历名称>大专</学历名称><入学时间>200907</入学时间><是否统招>1</是否统招><学校名称>福建交通</学校名称></学历信息><工作经历><公司名称>北京玖富时代投资顾问有限公司</公司名称><公司行业编码>500</公司行业编码><公司行业名称>信托/担保/拍卖/典当</公司行业名称><结束时间>201707</结束时间><开始时间>201403</开始时间><职称>经理</职称></工作经历></简历信息>";
        
        OSSClient ossClient = new OSSClient(endPoint,  accessKeyId, accessSecret);
        OSSClientUtil.setOssClient(ossClient);
        OSSClientUtil.setBucketName(bucketName);
        
        try{
        //  OSSClientUtil.uploadURLImg2OSS(new URL(fileURL), "test1234.jpg");
            File path = new File("D:\\data1\\jianli");
            File[] listFiles = path.listFiles();
            for (File file : listFiles) {
                String key = file.getName();
                System.out.println(key);
                InputStream in = new FileInputStream(file);
                String accessUrl = uploadFile2OSS(key, in, "CONTENT_TYPE_TXT");
                System.out.println(accessUrl);
                
            }
//          OSSClientUtil.uploadXML2OSS(strContent, "resume.xml");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

相关文章

网友评论

    本文标题:OSSClientUtil工具类

    本文链接:https://www.haomeiwen.com/subject/kjblgctx.html