JAVA整合OSS 之 阿里云, 腾讯云,七牛云

阿里云

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
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;

public class AliyunOSSHelper {

    private String bucketName;

    private OSSClient ossClient;

    public AliyunOSSHelper(String endpoint, String accessKeyId, String accessKeySecret, String bucketName) {
        this.bucketName = bucketName;
        this.ossClient = (OSSClient) new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    }

    public String upload(InputStream ins, String filePathName) {
        if (filePathName.startsWith("/")) {
            filePathName = filePathName.substring(1);
        }
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePathName, ins);
        ossClient.putObject(putObjectRequest);
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
        URL url = ossClient.generatePresignedUrl(bucketName, filePathName, expiration);
        return url.toString();
    }

    public String upload(File file, String filePathName) {
        try {
            return upload(new FileInputStream(file), filePathName);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public String upload(BufferedImage image, String filePathName) {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "PNG", result);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return upload(new ByteArrayInputStream(result.toByteArray()), filePathName);
    }

}

腾讯云

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.Date;

public class TencentOSSHelper {

    private String bucketName;

    private COSClient cosClient;

    public TencentOSSHelper(String secretId, String secretKey, String region, String bucketName){
        COSCredentials cred = new BasicCOSCredentials(secretId,secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        this.cosClient = new COSClient(cred, clientConfig);
        this.bucketName = bucketName;
    }

    public String upload(InputStream inputStream, String filePathName){
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filePathName, inputStream, new ObjectMetadata());
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 100);
        URL url = cosClient.generatePresignedUrl(bucketName,filePathName, expiration);
        //组装url,经过测试,与阿里云不同,腾讯云不能通过url.toString()获得url,但是能够通过规则http:// + 图片地址 + / + 地址获得url
        String uriOutput = url.getProtocol() + "://" + url.getHost() + "/"+ filePathName;
        return uriOutput;
    }

    public String upload(File file, String filePathName) {
        try {
            return upload(new FileInputStream(file), filePathName);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    public String upload(BufferedImage image, String filePathName) {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "PNG", result);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return upload(new ByteArrayInputStream(result.toByteArray()), filePathName);
    }
}

七牛云

import com.qiniu.common.QiniuException;
import com.qiniu.common.Region;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class QiniuHelper {

    private static final UploadManager UPLOAD_MANAGER = new UploadManager(new Configuration());
    private String accessKey;
    private String secretKey;
    private String bucket;
    private String cndDomain;
    private int uploadRetryTimes = 3;

    public QiniuHelper(String accessKey, String secretKey, String bucket, String cndDomain) {
        this(accessKey, secretKey, bucket, cndDomain, 3);
    }

    public QiniuHelper(String accessKey, String secretKey, String bucket, String cndDomain, int uploadRetryTimes) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
        this.bucket = bucket;
        this.cndDomain = cndDomain;
        if (uploadRetryTimes <= 0) {
            uploadRetryTimes = 3;
        } else if (uploadRetryTimes > 20) {
            uploadRetryTimes = 20;
        }
        this.uploadRetryTimes = uploadRetryTimes;
    }

    public static String upToken(String accessKey, String secretKey, String bucket) {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        return upToken;
    }

    public String upToken() {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        return upToken;
    }

    public String upToken(Long ttlSecond) {
        Auth auth = Auth.create(accessKey, secretKey);
        if (ttlSecond == null || ttlSecond <= 1) {
            return upToken();
        }
        String upToken = auth.uploadToken(bucket, (String) null, ttlSecond, (StringMap) null, true);
        return upToken;
    }

    public String upToken(String key, long expires, StringMap policy, boolean strict) {
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket, key, expires, policy, strict);
        return upToken;
    }

    public String upload(File file, String fileName) {
        RuntimeException ex = new RuntimeException("七牛图片上传失败[未知错误]");
        for (int i = 0; i < uploadRetryTimes; i++) {
            String token = upToken();
            try {
                Response response = UPLOAD_MANAGER.put(file, fileName, token);
                if (response.isOK()) {
                    return cndDomain + fileName;
                }
                ex = new RuntimeException("七牛图片上传失败[" + response.bodyString() + "]");
            } catch (QiniuException e) {
                ex = new RuntimeException("七牛图片上传失败", e);
            }
        }
        throw ex;
    }

    public String upload(byte[] data, String fileName) {
        RuntimeException ex = new RuntimeException("七牛图片上传失败[未知错误]");
        for (int i = 0; i < uploadRetryTimes; i++) {
            String token = upToken();
            try {
                Response response = UPLOAD_MANAGER.put(data, fileName, token);
                if (response.isOK()) {
                    return cndDomain + fileName;
                }
                ex = new RuntimeException("七牛图片上传失败[" + response.bodyString() + "]");

            } catch (QiniuException e) {
                ex = new RuntimeException("七牛图片上传失败", e);
            }
        }
        throw ex;
    }

    public String upload(BufferedImage img, String fileName) {
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        try {
            ImageIO.write(img, "PNG", result);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
        return upload(result.toByteArray(), fileName);
    }

    public String upload(InputStream fileIs, String fileName) {
        RuntimeException ex = new RuntimeException("七牛图片上传失败[未知错误]");
        for (int i = 0; i < uploadRetryTimes; i++) {
            String token = upToken();
            try {
                Response response = UPLOAD_MANAGER.put(fileIs, fileName, token, null, null);
                if (response.isOK()) {
                    return cndDomain + fileName;
                }
                ex = new RuntimeException("七牛图片上传失败[" + response.bodyString() + "]");

            } catch (QiniuException e) {
                ex = new RuntimeException("七牛图片上传失败", e);
            }
        }
        throw ex;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值