博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用阿里云对象存储OSS上传图片工具类
阅读量:5971 次
发布时间:2019-06-19

本文共 5324 字,大约阅读时间需要 17 分钟。

package com.verse.hades.utils;import com.aliyun.oss.OSSClient;import com.aliyun.oss.common.auth.CredentialsProvider;import com.aliyun.oss.common.auth.DefaultCredentialProvider;import com.aliyun.oss.model.ObjectMetadata;import com.aliyun.oss.model.PutObjectResult;import com.verse.hades.config.OSSConfig;import lombok.extern.slf4j.Slf4j;import org.springframework.web.multipart.MultipartFile;import java.io.*;import java.net.URL;import java.util.Date;@Slf4jpublic class OSSClientUtil {    //阿里云OSS API的内或外网域名    private static String ENDPOINT;    //阿里云OSS API的密钥Access Key ID      private static String ACCESS_KEY_ID;    //阿里云OSS API的密钥Access Key Secret      private static String ACCESS_KEY_SECRET;    //阿里云OSS API的bucket名称      private static String BUCKET_NAME;    //阿里云OSS 上传文件夹    private static String IMAGE_FOLDER;    private static CredentialsProvider credentialsProvider;    private static final long IMAGE_EXPIRE_TIME = 10 * 365 * 24 * 60 * 60 * 1000L;//图片访问链接的过期时间    private static OSSClient ossClient;    public OSSClientUtil() {        ossClient = new OSSClient(ENDPOINT, credentialsProvider, null);    }    public static void setConfigInfo(OSSConfig ossClientConfig) {        OSSClientUtil.ENDPOINT = ossClientConfig.getEndpoint();        OSSClientUtil.ACCESS_KEY_ID = ossClientConfig.getAccessKeyId();        OSSClientUtil.ACCESS_KEY_SECRET = ossClientConfig.getAccessKeySecret();        OSSClientUtil.BUCKET_NAME = ossClientConfig.getBucketName();        OSSClientUtil.IMAGE_FOLDER = ossClientConfig.getImageFolder();        credentialsProvider = new DefaultCredentialProvider(ACCESS_KEY_ID, ACCESS_KEY_SECRET);    }    /**     * 初始化     */    public static void init() {        ossClient = new OSSClient(ENDPOINT, credentialsProvider, null);    }    /**     * 销毁     */    public static void destory() {        ossClient.shutdown();    }    /**     * @param: instream     * @param: fileName     * @Return: java.lang.String     * @Decription: 上传图片至OSS     * @CreateDate: Created in 2018/12/11 16:36     * @Modify:     */    public static String uploadImageToOSS(MultipartFile file, String fileName) {        if (ossClient == null) {            init();        }        String ret = "";        try {            //创建上传Object的Metadata            ObjectMetadata objectMetadata = new ObjectMetadata();            objectMetadata.setContentLength(file.getInputStream().available());            objectMetadata.setCacheControl("no-cache");            objectMetadata.setHeader("Pragma", "no-cache");            objectMetadata.setContentType(getcontentType(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."))));            objectMetadata.setContentDisposition("inline;filename=" + fileName);            //上传文件            PutObjectResult putResult = ossClient.putObject(BUCKET_NAME, IMAGE_FOLDER + fileName, file.getInputStream(), objectMetadata);            ret = putResult.getETag();        } catch (IOException e) {            log.error("upload file to oss error name={}", fileName, e);        } finally {            try {                if (file.getInputStream() != null) {                    file.getInputStream().close();                }            } catch (Exception e) {                e.printStackTrace();            }        }        return ret;    }    /**     * @param: FilenameExtension     * @Return: java.lang.String     * @Decription: 判断OSS服务文件上传时文件的contentType     * @CreateDate: Created in 2018/12/11 17:19     * @Modify:     */    private 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";    }    /**     * @param: fileName     * @Return: java.lang.String     * @Decription: 根据图片名称获取图片访问地址     * @CreateDate: Created in 2018/12/11 17:18     * @Modify:     */    public static String getImageUrl(String fileName) {        // 设置URL过期时间        Date expiration = new Date(new Date().getTime() + IMAGE_EXPIRE_TIME);        // 生成URL        URL url = ossClient.generatePresignedUrl(BUCKET_NAME, IMAGE_FOLDER + fileName, expiration);        if (url != null) {            return url.toString();        }        return null;    }}

 

转载于:https://www.cnblogs.com/JoeyWong/p/11041096.html

你可能感兴趣的文章
WEB程序员需要掌握的十大MySQL优化技巧
查看>>
JavaScript事件对象
查看>>
一.操作系统
查看>>
导出excel表格,前端和后台导出
查看>>
m邻接
查看>>
两边对齐
查看>>
antd中的form表单 initialValue导致数据不更新问题
查看>>
sqlserver2008中如何用右键可视化的设置外键
查看>>
P1088 火星人
查看>>
面向对象的7种原则
查看>>
Javascript定时器
查看>>
递归,记忆化搜索,(棋盘分割)
查看>>
网格中的BFS,逆向(POJ2049)
查看>>
Sublime Text 2/3 Package Control 安装方法(Install Package)
查看>>
Leetcode题目:Rectangle Area
查看>>
(转载)jQuery 1.6 源码学习(一)——core.js[1]之基本架构
查看>>
软件工程第二次作业
查看>>
改变textFiled中placeholder的字体颜色的方法以及不想光标在textView的最左边设置方法...
查看>>
UVA11825 黑客的攻击 Hackers' Crackdown 状压DP,二进制,子集枚举
查看>>
[工具]各种截图工具和录屏软件
查看>>