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

阿里OSS前端直传

程序员文章站 2022-06-29 08:23:04
第一次写博客,如有错误请多多指教。 先上代码吧: 上传用的是sts上传还需要在阿里云进行一系列的授权管理,最后得到AccessKeyId,AccessKeySecret用来请求已经授权的角色(RoleArn)当然还需要REGIONID(地区对应ID 例:cn-beijing),ENDPOINT(请求 ......

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

先上代码吧:

 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     }

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