阿里OSS前端直传

发布时间:2019-06-04 22:00:22发布者:Mr.Zhang阅读(234)

第一次写博客,如有错误请多多指教。

先上代码吧:

 1 ossUpload = function (file, fun, funParameter) {
 2     //第一此请求后台服务器获取认证请求
 3     $.ajax({
 4         url: "/UEditor/GetSecurityToken",
 5         type: "post",
 6         success: function (data) {
 7             var access = JSON.parse(data);
 8             console.log(access);
 9             let host = access.Host;
10             var myDate = new Date().format("yyyyMMddhhmmss");
11             var policyBase64 = Base64.encode(JSON.stringify(myDate))
12             var name = Base64.encode(JSON.stringify(myDate))
13             var name = Crypto.HMAC(Crypto.SHA1, policyBase64, name);
14             var g_object_name = access.Object_name + "/" + name+"."+file.type.split('/')[1]
15             var request = new FormData();
16             request.append('id', "file_0");
17             request.append("OSSAccessKeyId", access.AccessKeyId); //Bucket 拥有者的Access Key Id。
18             request.append("policy", access.Policy); //policy规定了请求的表单域的合法性
19             request.append("Signature", access.Signature); //根据Access Key Secret和policy计算的签名信息,OSS验证该签名信息从而验证该Post请求的合法性
20             request.append('x-oss-security-token', access.SecurityToken);
21             //---以上都是阿里的认证策略 
22             request.append("key", g_object_name); //文件名字,可设置路径
23             request.append("success_action_status", '200'); // 让服务端返回200,不然,默认会返回204
24             request.append('file', file); //需要上传的文件 file  
25             console.log(request);
26             //正式上传请求
27             $.ajax({
28                 url: host, //上传阿里地址
29                 data: request,
30                 processData: false, //默认true,设置为 false,不需要进行序列化处理
31                 cache: false, //设置为false将不会从浏览器缓存中加载请求信息
32                 async: false, //发送同步请求
33                 contentType: false, //避免服务器不能正常解析文件---------具体的可以查下这些参数的含义
34                 dataType: 'xml', //不涉及跨域  写json即可
35                 type: 'post',
36                 success: fun(funParameter, host, g_object_name),
37                 error: function (returndata) {
38                     console.log(arguments)
39                     alert("上传图片出错", false);
40                 }
41             });
42         }
43     })
44 }
45 //格式化时间
46 Date.prototype.format = function (fmt) {
47     var o = {
48         "M+": this.getMonth() + 1,                 //月份 
49         "d+": this.getDate(),                    //日 
50         "h+": this.getHours(),                   //小时 
51         "m+": this.getMinutes(),                 //分 
52         "s+": this.getSeconds(),                 //秒 
53         "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
54         "S": this.getMilliseconds()             //毫秒 
55     };
56     if (/(y+)/.test(fmt)) {
57         fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
58     }
59     for (var k in o) {
60         if (new RegExp("(" + k + ")").test(fmt)) {
61             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
62         }
63     }
64     return fmt;
65 }

上传用的是sts上传还需要在阿里云进行一系列的授权管理,最后得到AccessKeyId,AccessKeySecret用来请求已经授权的角色(RoleArn)当然还需要REGIONID(地区对应ID 例:cn-beijing),ENDPOINT(请求接口 例:sts.cn-beijing.aliyuncs.com)

这一步sts请求是在后台进行的我后台用的是.net core,还需要引用aliyun-net-sdk-sts上一份后端的代码

 1  public class AliyunAcsStsConfig
 2     {
 3         /// <summary>
 4         /// 地区
 5         /// </summary>
 6         public string REGIONID { get; set; }
 7         /// <summary>
 8         /// 访问阿里云的地址
 9         /// </summary>
10         public string ENDPOINT { get; set; }
11         /// <summary>
12         /// 配置的ram
13         /// </summary>
14         public string RoleArn { get; set; }
15         /// <summary>
16         /// 会话的名称可自定义
17         /// </summary>
18         public string RoleSessionName { get; set; }
19         /// <summary>
20         /// 该权限用户的密码
21         /// </summary>
22         public string AccessKeySecret { get; set; }
23         /// <summary>
24         /// 该权限的用户ID
25         /// </summary>
26         public string AccessKeyId { get; set; }
27         /// <summary>
28         /// 上传路径
29         /// https://Bucket名称.oss-cn-beijing.aliyuncs.com
30         /// </summary>
31         public string upload { get; set; }
32         /// <summary>
33         /// 文件存储路径
34         /// ***/****/
35         /// </summary>
36         public string path { get; set; }
37     }     


private readonly UEditorService _ueditorService; private readonly AliyunAcsStsConfig stsConfig; public UEditorController(UEditorService ueditorService, IOptions<AliyunAcsStsConfig> stsConfig) { this._ueditorService = ueditorService; this.stsConfig = stsConfig.Value; }

 

 string REGIONID = stsConfig.REGIONID;
            string ENDPOINT = stsConfig.ENDPOINT;
            // 构建一个 Aliyun Client, 用于发起请求
            // 构建Aliyun Client时需要设置AccessKeyId和AccessKeySevcret
            DefaultProfile.AddEndpoint(REGIONID, REGIONID, "Sts", ENDPOINT);
            IClientProfile profile = DefaultProfile.GetProfile(REGIONID, stsConfig.AccessKeyId, stsConfig.AccessKeySecret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            // 构造AssumeRole请求
            AssumeRoleRequest request = new AssumeRoleRequest();
            request.AcceptFormat = FormatType.JSON;
            // 指定角色Arn
            request.RoleArn = stsConfig.RoleArn;
            request.RoleSessionName = stsConfig.RoleSessionName;
            // 可以设置Token有效期,可选参数,默认3600秒;
            // request.DurationSeconds = 3600;
            // 可以设置Token的附加Policy,可以在获取Token时,通过额外设置一个Policy进一步减小Token的权限;
            // request.Policy="<policy-content>"
            String dt = DateTime.Now.AddMinutes(5).ToString("yyyy-MM-ddTHH:mm:ss.000Z");
            object[,] ob = { { "content-length-range", 0, 1048576000 } };
            AssumeRoleResponse response = client.GetAcsResponse(request);
            ImgUploadAccess access = new ImgUploadAccess();
            access.AccessKeyId = response.Credentials.AccessKeyId;
            access.AccessKeySecret = response.Credentials.AccessKeySecret;
            access.SecurityToken = response.Credentials.SecurityToken;
            string str = JsonConvert.SerializeObject(new Policy
            {
                expiration=dt,
                conditions=ob
            });
            byte[] b = Encoding.Default.GetBytes(str);
            string base64 = Convert.ToBase64String(b);
            HMACSHA1 hmacsha1 = new HMACSHA1();
            hmacsha1.Key= Encoding.UTF8.GetBytes(access.AccessKeySecret);
            byte[] hashBytes = hmacsha1.ComputeHash(Encoding.UTF8.GetBytes(base64));
            access.Policy = base64;
            access.Signature =Convert.ToBase64String(hashBytes);
            access.Object_name = stsConfig.path+DateTime.Now.ToString("yyyyMM");
            access.Host = stsConfig.imgupload;
            return JsonConvert.SerializeObject(access);

 

 1   public class ImgUploadAccess
 2     {
 3         public string AccessKeyId { get; set; }
 4         public string AccessKeySecret { get; set; }
 5         public string SecurityToken { get; set; }
 6         public string Host { get; set; }
 7         public string Signature { get; set; }
 8         public string Policy { get; set; }
 9         public string Object_name { get; set; }
10     }
11     public class Policy
12     {
13         public string expiration { get; set; }
14         public object[,] conditions { get; set; }
15     }

 这样上传功能基本上搞定了





本文转自博客园,原文地址:https://www.cnblogs.com/MTCS/p/10973465.html