使用 REST 将文件上传到媒体服务帐户Upload files into a Media Services account using REST

在媒体服务中,可以将数字文件上传到资产中。In Media Services, you upload your digital files into an asset. 资产实体可以包含视频、音频、图像、缩略图集合、文本轨道和隐藏式字幕文件(以及这些文件的相关元数据。)将文件上传到资产后,相关内容即安全地存储在云中供后续处理和流式处理。The Asset entity can contain video, audio, images, thumbnail collections, text tracks and closed caption files (and the metadata about these files.) Once the files are uploaded into the asset, your content is stored securely in the cloud for further processing and streaming.

本教程介绍如何上传文件及其关联的其他操作:In this tutorial, you learn how to upload a file and other operation associated with it:

  • 为所有上传操作设置 PostmanSet up Postman for all the upload operations
  • 连接到媒体服务Connect to Media Services
  • 创建具有写入权限的访问策略。Create an access policy with write permission
  • 创建资产Create an asset
  • 创建 SAS 定位符并创建上传 URLCreate a SAS locator and create the upload URL
  • 使用上传 URL 将文件上传到 Blob 存储Upload a file to blob storage using the upload URL
  • 在资产中为上传的媒体文件创建元数据Create a metadata in the asset for the media file you uploaded

先决条件Prerequisites

注意事项Considerations

使用媒体服务 REST API 时,需注意以下事项:The following considerations apply when using Media Services REST API:

  • 访问媒体服务 REST API 访问实体时,必须在 HTTP 请求中设置特定标头字段和值。When accessing entities using Media Services REST API, you must set specific header fields and values in your HTTP requests. 有关详细信息,请参阅媒体服务 REST API 开发的设置For more information, see Setup for Media Services REST API Development.
    本教程中使用的 Postman 集合负责设置所有必要的标头。The Postman collection used in this tutorial takes care of setting all the necessary headers.
  • 构建流内容的 URL 时,媒体服务会使用 IAssetFile.Name 属性的值(如 http://{AMSAccount}.origin.mediaservices.chinacloudapi.cn/{GUID}/{IAssetFile.Name}/streamingParameters。)出于这个原因,不允许使用百分号编码。Media Services uses the value of the IAssetFile.Name property when building URLs for the streaming content (for example, http://{AMSAccount}.origin.mediaservices.chinacloudapi.cn/{GUID}/{IAssetFile.Name}/streamingParameters.) For this reason, percent-encoding is not allowed. Name 属性的值不能含有任何以下百分号编码保留字符:!*'();:@&=+$,/?%#[]"。The value of the Name property cannot have any of the following percent-encoding-reserved characters: !*'();:@&=+$,/?%#[]". 此外,文件扩展名中只能含有一个“.”。Also, there can only be one '.' for the file name extension.
  • 名称长度不应超过 260 个字符。The length of the name should not be greater than 260 characters.
  • 在媒体服务中进行处理时,系统支持的最大文件大小存在限制。There is a limit to the maximum file size supported for processing in Media Services. 有关文件大小限制的详细信息,请参阅此文See this article for details about the file size limitation.

设置 PostmanSet up Postman

有关如何为本教程设置 Postman 的步骤,请参阅配置 PostmanFor steps on how to set up Postman for this tutorial, see Configure Postman.

连接到媒体服务Connect to Media Services

  1. 将连接值添加到环境。Add connection values to your environment.

    在开始执行集合中定义的操作之前,需要手动设置 MediaServices 环境中的某些变量。Some variables that are part of the MediaServices environment need to be set manually before you can start executing operations defined in the collection.

    若要获取前五个变量的值,请参阅通过 Azure AD 身份验证访问 Azure 媒体服务 APITo get values for the first five variables, see Access the Azure Media Services API with Azure AD authentication.

    上传文件

  2. 指定 MediaFileName 环境变量的值。Specify the value for the MediaFileName environment variable.

    指定要上传的媒体的文件名。Specify the file name of the media you are planning to upload. 在此示例中,我们要上传 BigBuckBunny.mp4。In this example, we are going to upload the BigBuckBunny.mp4.

  3. 检查 AzureMediaServices.postman_environment.json 文件。Examine the AzureMediaServices.postman_environment.json file. 可以看到,集合中的几乎所有操作都执行“test”脚本。You will see that almost all operations in the collection execute a "test" script. 这些脚本采用响应返回的某些值,并设置相应的环境变量。The scripts take some values returned by the response and set appropriate environment variables.

    例如,第一个操作获取访问令牌,并在用于所有其他操作的 AccessToken 环境变量中设置该令牌。For example, the first operation gets an access token and set it on the AccessToken environment variable that is used in all other operations.

    "listen": "test",
    "script": {
        "type": "text/javascript",
        "exec": [
            "var json = JSON.parse(responseBody);",
            "postman.setEnvironmentVariable(\"AccessToken\", json.access_token);"
        ]
    }
    
  4. 在“Postman”窗口的左侧,单击“1. 获取 AAD 身份验证令牌” -> “获取服务主体的 Azure AD 令牌”。On the left of the Postman window, click on 1. Get AAD Auth token -> Get Azure AD Token for Service Principal.

    URL 部分填入 AzureADSTSEndpoint 环境变量(在本教程的前面部分,设置了支持集合的环境变量的值)。The URL portion is filled with the AzureADSTSEndpoint environment variable (earlier in the tutorial, you set the values of environment variables that support the collection).

    上传文件

  5. 按“发送”。 Press Send.

    可以看到包含“access_token”的响应。You can see the response that contains "access_token". “test”脚本采用此值,并设置 AccessToken 环境变量(如前所述)。The "test" script takes this value and sets the AccessToken environment variable (as described above). 如果检查环境变量的话,将会看到,此变量现在包含剩余操作中使用的访问令牌(持有者令牌)值。If you examine your environment variables, you will see that this variable now contains the access token (bearer token) value that is used in the rest of the operations.

    如果该令牌已过期,请再次执行“获取服务主体的 Azure AD 令牌”步骤。If the token expires go through the "Get Azure AD Token for Service Principal" step again.�

创建具有写入权限的访问策略。Create an access policy with write permission

概述Overview

备注

不同 AMS 策略的策略限制为 1,000,000 个(例如,对于定位器策略或 ContentKeyAuthorizationPolicy)。There is a limit of 1,000,000 policies for different AMS policies (for example, for Locator policy or ContentKeyAuthorizationPolicy). 如果始终使用相同的日期/访问权限,则应使用相同的策略 ID,例如,用于要长期就地保留的定位符的策略(非上传策略)。You should use the same policy ID if you are always using the same days / access permissions, for example, policies for locators that are intended to remain in place for a long time (non-upload policies). 有关详细信息,请参阅本文For more information, see this article.

将任何文件上传到 blob 存储之前,请设置用于对资产执行写入操作的访问策略权限。Before uploading any files into blob storage, set the access policy rights for writing to an asset. 为此,请向 AccessPolicy 实体集发送一个 HTTP POST 请求。To do that, POST an HTTP request to the AccessPolicies entity set. 请在执行创建操作时定义 DurationInMinutes 值,否则会在响应中收到 500 内部服务器错误消息。Define a DurationInMinutes value upon creation or you receive a 500 Internal Server error message back in response. 有关 AccessPolicies 的详细信息,请参阅 AccessPolicyFor more information on AccessPolicies, see AccessPolicy.

创建访问策略Create an access policy

  1. 选择“AccessPolicy” -> “创建要上传的 AccessPolicy”。 Select AccessPolicy -> Create AccessPolicy for Upload.

  2. 按“发送”。 Press Send.

    上传文件

    “test”脚本将获取 AccessPolicy ID,并设置相应的环境变量。The "test" script gets the AccessPolicy Id and sets the appropriate environment variable.

创建资产Create an asset

概述Overview

资产是媒体服务中多种类型的对象或多组对象(包括视频、音频、图像、缩略图集合、文本轨道和隐藏的解释性字幕文件)的容器。An asset is a container for multiple types or sets of objects in Media Services, including video, audio, images, thumbnail collections, text tracks, and closed caption files. 在 REST API 中,创建资产需要向媒体服务发送 POST 请求,并将任何有关资产的属性信息放入请求正文中。In the REST API, creating an Asset requires sending POST request to Media Services and placing any property information about your asset in the request body.

在创建资产时可以添加的属性之一是 OptionsOne of the properties that you can add when creating an asset is Options. 可以指定以下加密选项之一:None(默认值,不使用加密)、StorageEncrypted(适用于已使用客户端存储加密预先加密的内容)、CommonEncryptionProtectedEnvelopeEncryptionProtectedYou can specify one of the following encryption options: None (default, no encryption is used), StorageEncrypted (for content that has been pre-encrypted with client-side storage encryption), CommonEncryptionProtected, or EnvelopeEncryptionProtected. 如果资产已加密,则需要配置传送策略。When you have an encrypted asset, you need to configure a delivery policy. 有关详细信息,请参阅配置资产传送策略For more information, see Configuring asset delivery policies.

如果资产要使用加密,必须按以下文章中所述创建 ContentKey 并将其链接到资产:如何创建 ContentKeyIf your asset is encrypted, you must create a ContentKey and link it to your asset as described in the following article: How to create a ContentKey. 将文件上传到资产后,需要使用加密资产期间获取的值更新 AssetFile 实体上的加密属性。After you upload the files into the asset, you need to update the encryption properties on the AssetFile entity with the values you got during the Asset encryption. 使用 MERGE HTTP 请求完成此操作。Do it by using the MERGE HTTP request.

本示例将创建一个不加密的资产。In this example, we are creating an unencrypted asset.

创建资产Create an asset

  1. 选择“资产” -> “创建资产”。 Select Assets -> Create Asset.

  2. 按“发送”。 Press Send.

    上传文件

    “test”脚本将获取 Asset ID,并设置相应的环境变量。The "test" script gets the Asset Id and sets the appropriate environment variable.

创建 SAS 定位符并创建上传 URLCreate a SAS locator and create the Upload URL

概述Overview

设置 AccessPolicy 和定位符后,即可使用 Azure 存储 REST API 将实际文件上传到 Azure BLOB 存储容器。Once you have the AccessPolicy and Locator set, the actual file is uploaded to an Azure Blob Storage container using the Azure Storage REST APIs. 必须将文件作为块 blob 上传。You must upload the files as block blobs. 页 blob 不受 Azure 媒体服务支持。Page blobs are not supported by Azure Media Services.

有关使用 Azure 存储 blob 的详细信息,请参阅 Blob 服务 REST APIFor more information on working with Azure storage blobs, see Blob Service REST API.

若要检索实际上传 URL,请创建一个 SAS 定位符(参阅下文)。To receive the actual upload URL, create a SAS Locator (shown below). 定位符为希望访问资产中文件的客户端定义连接终结点的开始时间和类型。Locators define the start time and type of connection endpoint for clients that want to access Files in an Asset. 可以为给定 AccessPolicy 和资产对创建多个定位符实体,以处理不同的客户端请求和需求。You can create multiple Locator entities for a given AccessPolicy and Asset pair to handle different client requests and needs. 这其中的任一定位符都可使用 AccessPolicy 的 StartTime 值和 DurationInMinutes 值来确定可以使用某 URL 的时间长度。Each of these Locators uses the StartTime value plus the DurationInMinutes value of the AccessPolicy to determine the length of time a URL can be used. 有关详细信息,请参阅 定位符For more information, see Locator.

SAS URL 采用以下格式:A SAS URL has the following format:

{https://myaccount.blob.core.chinacloudapi.cn}/{asset name}/{video file name}?{SAS signature}

注意事项Considerations

请注意以下事项:Some considerations apply:

  • 一项给定的资产一次最多只能与五个唯一的定位符相关联。You cannot have more than five unique Locators associated with a given Asset at one time. 有关详细信息,请参阅定位符。For more information, see Locator.
  • 如果需要立即上传文件,应将 StartTime 值设置为当前时间前五分钟。If you need to upload your files immediately, you should set your StartTime value to five minutes before the current time. 这是因为客户端计算机与媒体服务之间可能存在时钟偏差。This is because there may be clock skew between your client machine and Media Services. 此外,StartTime 值必须采用以下 DateTime 格式:YYYY-MM-DDTHH:mm:ssZ(例如“2014-05-23T17:53:50Z”)。Also, your StartTime value must be in the following DateTime format: YYYY-MM-DDTHH:mm:ssZ (for example, "2014-05-23T17:53:50Z").
  • 定位符从创建到可用可能会有 30-40 秒的延迟。There may be a 30-40 second delay after a Locator is created to when it is available for use.

创建 SAS 定位符Create a SAS locator

  1. 选择“定位符” -> “创建 SAS 定位符”。 Select Locator -> Create SAS Locator.

  2. 按“发送”。 Press Send.

    “test”脚本将会根据指定的媒体文件名和 SAS 定位符信息创建“上传 URL”,并设置相应的环境变量。The "test" script creates the "Upload URL" based on the media file name you specified and SAS locator information and sets the appropriate environment variable.

    上传文件

使用上传 URL 将文件上传到 Blob 存储Upload a file to blob storage using the upload URL

概述Overview

创建上传 URL 后,需要直接使用 Azure Blob API 编写一些代码,用于将文件上传到 SAS 容器。Now that you have the upload URL, you need to write some code using the Azure Blob APIs directly to upload your file to the SAS container. 有关详细信息,请参阅以下文章:For more information, see the following articles:

使用 Postman 上传文件Upload a file with Postman

例如,我们使用 Postman 上传一个 .mp4 小文件。As an example, we use Postman to upload a small .mp4 file. 通过 Postman 上传二进制文件可能存在文件大小限制。There may be a file size limit on uploading binary through Postman.

上传请求不是 AzureMedia 集合的一部分。The upload request is not part of the AzureMedia collection.

创建并设置新请求:Create and set up a new request:

  1. + 创建新的请求选项卡。Press +, to create a new request tab.

  2. 选择“PUT”操作并在 URL 中粘贴 {{UploadURL}}Select PUT operation and paste {{UploadURL}} in the URL.

  3. 将“授权”选项卡保留原样(不要将其设置为“持有者令牌”)。 Leave Authorization tab as is (do not set it to the Bearer Token).

  4. 在“标头” 选项卡中,指定::“x-ms-blob-type”和:“BlockBlob”。In the Headers tab, specify: Key: "x-ms-blob-type" and Value: "BlockBlob".

  5. 在“正文”选项卡中,单击“二进制”。 In the Body tab, click binary.

  6. 选择具有 MediaFileName 环境变量中指定的名称的文件。Choose the file with the name that you specified in the MediaFileName environment variable.

  7. 按“发送”。 Press Send.

    上传文件

在资产中创建元数据Create a metadata in the asset

上传文件后,需要在已上传到与资产关联的 Blob 存储的媒体文件的资产中创建元数据。Once the file has been uploaded, you need to create a metadata in the asset for the media file you uploaded into the blob storage associated with your asset.

  1. 选择“AssetFiles” -> “CreateFileInfos”。 Select AssetFiles -> CreateFileInfos.

  2. 按“发送”。 Press Send.

    上传文件

随后应会上传该文件及其元数据。The file should be uploaded and its metadata set.

验证Validate

若要验证是否已成功上传文件,可以查询 AssetFile,并将 ContentFileSize(或其他详细信息)与希望在新资产中显示的信息进行比较。To validate that the file has been uploaded successfully, you might want to query the AssetFile and compare the ContentFileSize (or other details) to what you expect to see in the new asset.

例如,以下 GET 操作将获取资产文件(在本例中为 BigBuckBunny.mp4 文件)的文件数据。For example, the following GET operation brings file data for your asset file (in or case, the BigBuckBunny.mp4 file). 该查询使用前面设置的环境变量The query is using the environment variables that you set earlier.

{{RESTAPIEndpoint}}/Assets('{{LastAssetId}}')/Files

响应中将会包含大小、名称和其他信息。Response will contain size, name, and other information.

"Id": "nb:cid:UUID:69e72ede-2886-4f2a-8d36-80a59da09913",
"Name": "BigBuckBunny.mp4",
"ContentFileSize": "3186542",
"ParentAssetId": "nb:cid:UUID:0b8f3b04-72fb-4f38-8e7b-d7dd78888938",
        

后续步骤Next steps

现即可编码已上传的资产。You can now encode your uploaded assets. 有关详细信息,请参阅对资产进行编码For more information, see Encode assets.

也可使用 Azure Functions 根据到达已配置容器的文件触发编码作业。You can also use Azure Functions to trigger an encoding job based on a file arriving in the configured container. 有关详细信息,请参阅此示例For more information, see this sample.