欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

oss进阶

程序员文章站 2022-07-10 18:11:28
...

oss是对象存储系统。

1.获取临时授权访问oss的token

package cn.hls.xjx.util.ossUtil;

import cn.hls.xjx.constant.Constant;
import cn.hls.xjx.util.IDUtil;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.aliyuncs.sts.model.v20150401.AssumeRoleRequest;
import com.aliyuncs.sts.model.v20150401.AssumeRoleResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 *@Description STS临时授权访问OSS
 *@ClassName OssSecurityTokenUtil
 *@Author hasee
 *@Date 2020/2/11 14:45
 *@Version 1.0
 */
public class OssSecurityTokenUtil {
    public static Map<String,Object> getToken() {
        Map<String,Object> result = new HashMap<>();
        String id= IDUtil.getUUID().substring(0,16);
        id=id.replace(id.substring(0,1),"ossId");
        Map<String, String> tokenMessage = getSTSToken(id);
        if (tokenMessage.size() == 0) {
            result.put("status", 0);
            result.put("desc", "请求失败!");
            return result;
        }
        result.put("Expiration", tokenMessage.get("Expiration"));
        result.put("AccessKey", tokenMessage.get("AccessKey"));
        result.put("AccessKeySecret", tokenMessage.get("AccessKeySecret"));
        result.put("SecurityToken", tokenMessage.get("SecurityToken"));
        result.put("endpoint", OssProFileConstant.endpoint);
        result.put("bucket", OssProFileConstant.bucket);
        result.put("status", 1);
        result.put("desc", "请求成功!");
        return result;
    }

    public static JSONObject getServerCode(HttpServletRequest request) {
        JSONObject result = new JSONObject();
        result.put("serverCode", Constant.serverCode);
        return result;
    }

    public static Map<String, String> getSTSToken(String userId) {
        Map<String, String> tokenMessage = new HashMap<String, String>();
        try {
            // 添加endpoint(直接使用STS endpoint,前两个参数留空,无需添加region ID)
            DefaultProfile.addEndpoint("", "", "Sts", OssProFileConstant.endpoint);
            // 构造default profile(参数留空,无需添加region ID)
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", OssProFileConstant.accessKeyId, OssProFileConstant.accessKeySecret);
            // 用profile构造client
            DefaultAcsClient client = new DefaultAcsClient(profile);
            final AssumeRoleRequest request = new AssumeRoleRequest();
            request.setMethod(MethodType.POST);
            request.setRoleArn(OssProFileConstant.roleArn);
            //使用当前的用户id作为session名称
            request.setRoleSessionName(userId);
            request.setPolicy(OssProFileConstant.policy); // Optional
            request.setDurationSeconds(900L);
            final AssumeRoleResponse response = client.getAcsResponse(request);
            tokenMessage.put("Expiration", response.getCredentials().getExpiration());
            tokenMessage.put("AccessKey", response.getCredentials().getAccessKeyId());
            tokenMessage.put("AccessKeySecret", response.getCredentials().getAccessKeySecret());
            tokenMessage.put("SecurityToken", response.getCredentials().getSecurityToken());
            tokenMessage.put("RequestId", response.getRequestId());
        } catch (ClientException e) {
        }
        return tokenMessage;
    }
}

2.通过临时授权上传文件

package cn.hls.xjx.util.ossUtil;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Map;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.Callback;
import com.aliyun.oss.model.Callback.CalbackBodyType;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
/**
 * OSS上传工具
 * @author hmy
 */
public class OssUploadUtils {
    /**
     * 简单上传
     * @param type:1表示字符串,2表示本地文件(绝对路径),3表示网络文件地址,4表示文件流,5表示字节数组
     * @param objectName:表示上传文件到OSS时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg   不包含buket
     * @param content:字符串
     * @param url:文件地址
     * @param inputStream:文件流
     * @param bytes:字节数组
     */
    public static Boolean uploadOSS(Integer type,String objectName,String content,String url,InputStream inputStream,byte[] bytes){
        Map<String, Object> map = OssSecurityTokenUtil.getToken();
        // 创建OSSClient实例    试用sts授权生成临时的key和secret
        OSS ossClient = new OSSClientBuilder().build(OssProFileConstant.endpoint, map.get("AccessKey").toString(), map.get("AccessKeySecret").toString(), map.get("SecurityToken").toString());
        PutObjectRequest putObjectRequest = null;
        try {
            switch (type) {
                case 1:
                    // 上传字符串
                    putObjectRequest = new PutObjectRequest(OssProFileConstant.bucket, objectName,new ByteArrayInputStream(content.getBytes()));
                    ossClient.putObject(putObjectRequest);
                    break;
                case 2:
                    // 上传文件
                    putObjectRequest = new PutObjectRequest(OssProFileConstant.bucket, objectName, new File(url));
                    ossClient.putObject(putObjectRequest);
                    break;
                case 3:
                    // 上传网络流。
                    InputStream is = new URL(url).openStream();
                    ossClient.putObject(OssProFileConstant.bucket, objectName, is);
                    break;
                case 4:
                    // 上传文件流。
                    PutObjectResult putObjectResult = ossClient.putObject(OssProFileConstant.bucket, objectName, inputStream);
                    break;
                case 5:
                    // 上传Byte数组
                    putObjectRequest = new PutObjectRequest(OssProFileConstant.bucket, objectName,new ByteArrayInputStream(bytes));
                    ossClient.putObject(putObjectRequest);
                    break;
                default:
                    // 上传文件流。
                    ossClient.putObject(OssProFileConstant.bucket, objectName, inputStream);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient。
            ossClient.shutdown();
        }
        return true;
    }

    /**
     * 上传回调
     * @return
     */
    public static String callbackOSS(String descFileUrlName,Map<String, Object> map) throws IOException {
        String callbackUrl = "http://172.18.1.71:12080";
        // 创建OSSClient实例    试用sts授权生成临时的key和secret
        OSS ossClient = new OSSClientBuilder().build(OssProFileConstant.endpoint, map.get("AccessKey").toString(), map.get("AccessKeySecret").toString(), map.get("SecurityToken").toString());
        try {
            String content = "Hello OSS";
            PutObjectRequest putObjectRequest = new PutObjectRequest(OssProFileConstant.bucket, descFileUrlName,new ByteArrayInputStream(content.getBytes()));
            Callback callback = new Callback();
            callback.setCallbackUrl(callbackUrl);
//            callback.setCallbackHost("oss-cn-hangzhou.aliyuncs.com");
            callback.setCallbackBody("{\\\"bucket\\\":${bucket},\\\"object\\\":${object},"
                    + "\\\"mimeType\\\":${mimeType},\\\"size\\\":${size}" );
            callback.setCalbackBodyType(CalbackBodyType.JSON);
//            callback.addCallbackVar("x:var1", "value1");
//            callback.addCallbackVar("x:var2", "value2");
            putObjectRequest.setCallback(callback);

            PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
            byte[] buffer = new byte[1024];
            putObjectResult.getResponse().getContent().read(buffer);
            putObjectResult.getResponse().getContent().close();

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message: " + oe.getErrorMessage());
            System.out.println("Error Code:       " + oe.getErrorCode());
            System.out.println("Request ID:      " + oe.getRequestId());
            System.out.println("Host ID:           " + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message: " + ce.getMessage());
        } finally {
            ossClient.shutdown();
        }
        return "OK";
    }
}

3.url访问oss中的文件

    oss进阶

    示例:当  桶名为:shipinziyuan-1    分布地域是 beijing  则如下访问

     https://shipinziyuan-1.oss-cn-beijing.aliyuncs.com/shipinceshi/3.jpg

4.oss配置域名访问(一般是二级域名)

      oss进阶

     如绑定域名: up.xinjiaoxue.cn   点击提交后等待几分钟就可以如下访问:  

     https://up.xinjiaoxue.cn/shipinceshi/3.jpg

    ***实际上 up.xinjiaoxue.cn  替换了   shipinziyuan-1.oss-cn-beijing.aliyuncs.com

 

相关标签: oss