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

azure 上传blob到ams(CreateFromBlob)

程序员文章站 2022-04-09 08:37:09
遇到的错误:The destination storage credentials must contain the account key credentials,参数名: destinationStorageCredentials 解决方法:AccountName与AccountKey参数值错误 ......

遇到的错误:the destination storage credentials must contain the account key credentials,参数名: destinationstoragecredentials

解决方法:accountname与accountkey参数值错误

accountname就是存储账户名字

accountkey值获取方式:打开存储账户-->访问秘钥-->key1或者key2

azure上传资产sdk

    public class azuremediaservicecontroller : apicontroller
    {
        // read values from the app.config file.

        private static readonly string _aadtenantdomain =
            configurationmanager.appsettings["amsaadtenantdomain"];
        private static readonly string _restapiendpoint =
            configurationmanager.appsettings["amsrestapiendpoint"];
        private static readonly string _amsclientid =
            configurationmanager.appsettings["amsclientid"];
        private static readonly string _amsclientsecret =
            configurationmanager.appsettings["amsclientsecret"];

        private static cloudmediacontext _context = null;

        [httppost, route("api/azuremediaservice/delivervideo")]
        // get: amsdelivervideo
        public string delivervideo(string filename)
        {
            getcloudmediacontext();
            iasset inputasset = uploadfile(filename, assetcreationoptions.none);
            var strsasuri = publishassetgeturls(inputasset);
            return strsasuri;
        }
        /// <summary>
        /// 获取媒体文件上下文
        /// </summary>
        private void getcloudmediacontext()
        {
            azureadtokencredentials tokencredentials =
                new azureadtokencredentials(_aadtenantdomain,
                    new azureadclientsymmetrickey(_amsclientid, _amsclientsecret),
                    azureenvironments.azurecloudenvironment);

            var tokenprovider = new azureadtokenprovider(tokencredentials);

            _context = new cloudmediacontext(new uri(_restapiendpoint), tokenprovider);
        }

        /// <summary>
        /// 创建新资产并上传视频文件
        /// </summary>
        /// <param name="filename">上传文件名称,如:f:\bigbuck.mp4</param>
        static public iasset uploadfile(string filename, assetcreationoptions options)
        {
            iasset inputasset = _context.assets.createfromfile(
                filename,
                options,
                (af, p) =>
                {
                    console.writeline("uploading '{0}' - progress: {1:0.##}%", af.name, p.progress);
                });
            return inputasset;
        }
        static public string publishassetgeturls(iasset asset)
        {
            // publish the output asset by creating an origin locator for adaptive streaming,
            // and a sas locator for progressive download.
            //用于流媒体(例如 mpeg dash、hls 或平滑流式处理)的 ondemandorigin 定位符
            //_context.locators.create(
            //    locatortype.ondemandorigin,
            //    asset,
            //    accesspermissions.read,
            //    timespan.fromdays(30));

            //用于下载媒体文件的访问签名
            _context.locators.create(
                locatortype.sas,
                asset,
                accesspermissions.read,
                timespan.fromdays(30));


            ienumerable<iassetfile> mp4assetfiles = asset
                    .assetfiles
                    .tolist()
                    .where(af => af.name.endswith(".mp4", stringcomparison.ordinalignorecase));


            // get the urls for progressive download for each mp4 file that was generated as a result
            // of encoding.
            //list<uri> mp4progressivedownloaduris = mp4assetfiles.select(af => af.getsasuri()).tolist();
            string mp4progressivedownloaduris = mp4assetfiles.select(af => af.getsasuri()).firstordefault().originalstring;

            return mp4progressivedownloaduris;
            // display the urls for progressive download.   
            // mp4progressivedownloaduris.foreach(uri => console.writeline(uri + "\n"));    

        }


        string storageconnectionstring = configurationmanager.appsettings["storageconnectionstring"];
        string accountname = configurationmanager.appsettings["accountname"];
        string accountkey = configurationmanager.appsettings["accountkey"];

        /// <summary>
        /// 上传blob文件到ams中
        /// </summary>
        /// <param name="filename">文件名</param>
        public string uploadblobfile(string filename)
        {
            if (string.isnullorempty(filename))
                return string.empty;
            cloudstorageaccount storageaccount = null;
            cloudblobcontainer cloudblobcontainer = null;
            if (cloudstorageaccount.tryparse(storageconnectionstring, out storageaccount))
            {
                try
                {
                    // 创建cloudblobclient,它代表存储帐户的blob存储端点。
                    cloudblobclient cloudblobclient = storageaccount.createcloudblobclient();

                    //filename = "https://qdlsstorage.blob.core.windows.net/video/20190514165259-魔术视频.mp4";
                    //通过连接获取容器名字和文件名字
                    var index = filename.indexof(accountname, stringcomparison.currentcultureignorecase);
                    var temp = filename.substring(index + 1);
                    var fs = temp.split('/');
                    var containername = fs[1];
                    filename = fs[2]; 这一段代码根据你们自己的情况进行修改,我这个是因为传递的全路径才这么写的

                    // 获取blob容器 
                    cloudblobcontainer = cloudblobclient.getcontainerreference(containername);
                    getcloudmediacontext();
                    var storagecredentials = new storagecredentials(accountname, accountkey);
                    var cloudblockblob = cloudblobcontainer.getblockblobreference(filename);

                    cloudblockblob.fetchattributes();//这一句是关键,如果不加这一句就会报错,我把报错信息放到下面
                    var inputasset = _context.assets.createfromblob(cloudblockblob, storagecredentials, assetcreationoptions.none);
                    var strsasuri = publishassetgeturls(inputasset);
                    return strsasuri;
                }
                catch (exception e)
                {
                    console.writeline(e);
                }

            }

            return null;
        }
    }

 

报错信息:

<?xml version="1.0" encoding="utf-8"?><m:error xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><m:code /><m:message xml:lang="en-us">assetfile contentfilesize must not be negative</m:message></m:error>

参考地址:https://github.com/azure/azure-sdk-for-media-services-extensions/issues/40  (这是通过谷歌找到的资料,百度根本不行)

 

直接上传文件到资产中调用方法:

                var virtualpath = "/uploadfile/files/";
                        var path = httpcontext.current.server.mappath(virtualpath);
                        if (!directory.exists(path))
                        {
                            directory.createdirectory(path);
                        }
                        var filefullpath = $"{path}{filename}";
                        try
                        {
                            file.saveas(filefullpath);
                            var ams = new azuremediaservicecontroller();
                            url = ams.delivervideo(filefullpath);
                            result = true;
                            msg = $@"上传视频成功";
                            file.delete(filefullpath);
                        }
                        catch (exception ex)
                        {
                            msg = "上传文件写入失败:" + ex.innerexception + ex.message + ex.innerexception?.innerexception + "filefullpath=" + filefullpath;
                        }

因为使用的是html自带的file上传控件,传递给接口的文件地址全路径是错误的,所以只能保存到接口服务器本地,上传到azure上去之后再删除这个文件。

 

上传blob到ams

               var ams = new azuremediaservicecontroller();
                        var t = ams.uploadblobfile(fileurl);

 

上一篇: PHP新手上路(二)

下一篇: 追女孩