阿里云对象存储伪代码实例

package com.lianhebaoli.common.oss.client;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.CannedAccessControlList;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.PutObjectResult;
import com.lianhebaoli.cloud.common.utils.StringUtils;
import com.lianhebaoli.common.oss.config.AliyunConfig;
import com.lianhebaoli.common.oss.config.OssConfig;
import com.lianhebaoli.common.oss.exception.OSSException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.logging.log4j.util.PropertiesUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;

/**
 * All rights Reserved, Designed By kjt.gzst.gov.cn
 *
 * @version V1.0
 * @title: IOSSClient.java
 * @description: 阿里云的客户端操作
 * @author: chen.jinjie
 * @date: 2017年8月11日 下午9:55:00
 */
@Slf4j
public class AliyunOSSClient extends  AbstractOSSClient {
    public static final String DEFAULT_CONFIG_FILE = "aliyun.oss.properties";

    //阿里云客户端
    private OSSClient client;
    //阿里云API的内或外网域名
    private  String endpoint;
    //阿里云API的密钥Access Key ID
    private  String accessKeyId;
    //阿里云API的密钥Access Key Secret
    private  String accessKeySecret;
    //访问域名
    private  String domain;
    //bucket名称
    private String bucketName;

    private Boolean isPrivate;

    @Override
    public void init() {
      init(DEFAULT_CONFIG_FILE);
    }

    @Override
    public void init(String propertiesName) {
        PropertiesUtil p = new PropertiesUtil(propertiesName);
        endpoint = p.getStringProperty("aliyun.oss.endpoint");
        accessKeyId = p.getStringProperty("aliyun.oss.access-key-id");
        accessKeySecret = p.getStringProperty("aliyun.oss.access-key-secret");
        bucketName = p.getStringProperty("aliyun.oss.bucket-name");
        domain = p.getStringProperty("aliyun.oss.domain");
        isPrivate = p.getBooleanProperty("oss.aliyun.is-private");
        client=new OSSClient(endpoint,accessKeyId, accessKeySecret);
    }

    public void init(OssConfig config) {
        AliyunConfig aliyunConfig = config.getAliyun();
        endpoint = aliyunConfig.getEndpoint();
        accessKeyId = aliyunConfig.getAccessKeyId();
        accessKeySecret = aliyunConfig.getAccessKeySecret();
        bucketName = aliyunConfig.getBucketName();
        domain =  aliyunConfig.getDomain();
        client=new OSSClient(endpoint,accessKeyId, accessKeySecret);
    }

    /**
     * 一般不推荐使用
     * @return
     */
    public OSSClient getClient(){
       return this.client;
    }

    /**
     * 文件上传
     * @param inputStream
     * @param fileKey
     * @return
     */
    @Override
    public String upload(InputStream inputStream, String fileKey) {
        try {
            PutObjectResult putObjectResult = client.putObject(bucketName, fileKey, inputStream);
        } catch (Exception e) {
            throw new OSSException("上传文件失败", e);
        }
        if (StringUtils.endsWithIgnoreCase(fileKey, ".jpg")||StringUtils.endsWithIgnoreCase(fileKey, ".jpeg")||StringUtils.endsWithIgnoreCase(fileKey, ".png")) {
            //如果是图片设置只读权限
            client.setObjectAcl(bucketName,fileKey, CannedAccessControlList.PublicRead);
        }
        return domain + "/" + fileKey;
    }

    @Override
    public String upload(File file, String fileKey) {
        try {
            PutObjectResult putObjectResult = client.putObject(bucketName, fileKey, file);
        } catch (Exception e) {
            throw new OSSException("上传文件失败", e);
        }
        if (StringUtils.endsWithIgnoreCase(fileKey, ".jpg")||StringUtils.endsWithIgnoreCase(fileKey, ".jpeg")||StringUtils.endsWithIgnoreCase(fileKey, ".png")) {
            //如果是图片设置只读权限
            client.setObjectAcl(bucketName,fileKey, CannedAccessControlList.PublicRead);
        }
        return domain + "/" + fileKey;
    }

    @Override
    public String getDownloadUrl(String fileKey) {
        //ObjectAcl objectAcl = ossClient.getObjectAcl(bucketName, key);
        if(isPrivate){
            URL url = client.generatePresignedUrl(bucketName, fileKey, DateUtils.addHours(new Date(), 1));
            return url.toString().replaceFirst(URL_PREFIX_PATTERN, domain);
        }
        return domain + fileKey;
    }


    /**
     * @param fileKey 文件路径名称
     * @param fileSize 文件大小
     * @param response
     */
    public  void download(final String fileKey, Long fileSize, final HttpServletResponse response) {
        InputStream in = null;
        try {
            OSSObject ossObject = client.getObject(bucketName, fileKey);
            in = ossObject.getObjectContent();
            if (in != null) {
                try {
                    response.setContentType("text/html;charset=utf-8"); /* 设定相应类型 编码 */
                    response.setCharacterEncoding("UTF-8");
                    try (
                            BufferedInputStream bufferedInputStream = new BufferedInputStream(in);
                            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream())) {
                        response.setContentType("application/octet-stream");
                        final String originFileName = fileKey;
                        final String fileName = URLEncoder.encode(originFileName, "utf-8").replaceAll("\\+",
                                "%20");
                        if (StringUtils.endsWithIgnoreCase(originFileName, ".pdf")) {
                            response.setContentType("application/pdf");
                        } else if (StringUtils.endsWithIgnoreCase(originFileName, ".jpg")||StringUtils.endsWithIgnoreCase(originFileName, ".jpeg")) {
                            response.setContentType("image/jpeg");
                        }  else if (StringUtils.endsWithIgnoreCase(originFileName, ".png")) {
                            response.setContentType("image/png");
                        } else if (StringUtils.endsWithIgnoreCase(originFileName, ".gif")) {
                            response.setContentType("image/gif");
                        } else {
                            response.setContentType("application/octet-stream");
                            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
                        }
                        response.setHeader("Content-Length", String.valueOf(fileSize));
                        IOUtils.copy(bufferedInputStream, bufferedOutputStream);
                    } catch (final Exception e) {
                        log.error("下载文件发生错误!", e);
                        throw new OSSException(e);
                    }
                } catch (final Exception e) {
                    response.setContentType("application/json;charset=utf-8"); /* 设定相应类型 编码 */
                    response.setCharacterEncoding("UTF-8");
                    try {
                        response.getWriter().append("\"下载文件发生错误!\"");
                    } catch (final IOException e1) {
                    }
                    log.error("下载文件发生错误!", e);
                }


            }
        } catch (Exception e) {
            log.error("附件下载异常", e);
            throw new OSSException("文件下载异常");
        } finally {
            if(in!=null) {
                // 数据读取完成后,获取的流必须关闭,否则会造成连接泄漏,导致请求无连接可用,程序无法正常工作。
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("附件下载异常", e);
                    throw new OSSException("文件下载异常");
                }
            }

        }
    }

    @Override
    public void delete(String filename) {

        try {
            filename=filename.replace( domain + "/" ,"");
            client.deleteObject(bucketName, filename);
        } catch (Exception e) {
            throw new OSSException("删除文件失败", e);
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值