場景
視訊點播提供了豐富的
上傳方式包括
用戶端上傳、
服務端上傳等,但可能缺乏需要的語言版本(如 Go 等),此時可以直接基于 OSS 原生 SDK 進行上傳。
前提
在閱讀本文前,請先确定确實沒有您所需要語言版本的上傳 SDK,點播服務已提供:
- 用戶端上傳 SDK:
- 服務端上傳 SDK:
說明 也可以直接通路
SDK 下載下傳頁面下載下傳 SDK 和 Demo,如确實沒有您需要的版本,可以繼續閱讀本文再行開發。
準備工作
- 确認已開通點播服務并完成了相關配置。
- 确認已準備了 阿裡雲賬号 AccessKey ,并授予了上傳權限。
上傳步驟
- 通路點播服務擷取請參見 上傳位址和上傳憑證 說明 這一步還會建立視訊媒資記錄,傳回視訊 ID,請妥善儲存,後續可根據視訊 ID 進行視訊播放、管理和 AI 處理等。
- 解析上傳位址(UploadAddress) 和 上傳憑證(UploadAuth),得到 OSS 的上傳位址和授權資訊。解析方式請參見 上傳位址和憑證的解析
- 調用 OSS SDK 将視訊檔案上傳至指定的 bucket 中,注意使用 STS Auth 方式,且使用解析後的上傳位址和授權資訊進行初始化,不要使用自己的 AccessKey 等資訊。
代碼實作
- 核心代碼實作共分 4 步:
-
- 使用 AK 初始化 VOD 用戶端。
- 擷取視訊上傳位址和憑證。
- 使用上傳憑證和位址初始化 OSS 用戶端。
- 上傳本地檔案。
- 可以使用點播服務的接口 SDK, 擷取上傳位址和憑證
- 使用 OSS SDK 在服務端上傳,可參考如下版本:
-
- OSS-.NET-SDK。
- OSS-C-SDK。
- OSS-Go-SDK。
- OSS-Ruby-SDK。
- OSS-Java-SDK。
PHP 上傳示例
環境準備
- PHP 5.3+,可通過 php -v 指令檢視目前的 PHP 版本。
- cURL 擴充,可通過 php -m 指令檢視 curl 擴充是否已經安裝好。
安裝
- 在您的 PHP 項目中添加空檔案夾 aliyun-php-sdk 。
- 從 aliyun-openapi-php-sdk 下載下傳整個源碼,解壓後拷貝 aliyun-php-sdk-core 和 aliyun-php-sdk-vod 兩個檔案夾到 aliyun-php-sdk 目錄下。
- aliyun-oss-php-sdk 下載下傳最新的 OSS PHP SDK 的源碼,解壓 ZIP 檔案後添加檔案夾到 aliyun-php-sdk 目錄下。以下載下傳 v.2.2.4 Source code (zip) 為例,解壓後檔案夾為 aliyun-oss-php-sdk-2.2.4。
- 打開 aliyun-php-sdk/aliyun-php-sdk-core/Config.php 檔案,找到 "//config sdk auto load path." 在這行下面添加:
Autoloader::addAutoloadPath("aliyun-php-sdk-vod");
- 在代碼中引用 VOD 和 OSS 的檔案。示例如下:
require_once './aliyun-php-sdk/aliyun-php-sdk-core/Config.php'; // 假定您的源碼檔案和aliyun-php-sdk處于同一目錄。
require_once './aliyun-php-sdk/aliyun-oss-php-sdk-2.2.4/autoload.php';
use vod\Request\V20170321 as vod;
use OSS\OssClient;
use OSS\Core\OssException;
- 說明 更多資訊可參考 VOD PHP SDK 安裝 和 OSS PHP SDK 安裝
參考代碼
- 定義核心步驟的函數:
-
- 使用 AK 初始化 VOD 用戶端。示例如下:
function init_vod_client($accessKeyId, $accessKeySecret) {
$regionId = 'cn-shanghai'; // 根據點播接入服務所在的Region填寫,例如:接入服務在上海,則填cn-shanghai
$profile = DefaultProfile::getProfile($regionId, $accessKeyId, $accessKeySecret);
return new DefaultAcsClient($profile);
}
-
- 擷取視訊上傳位址和憑證。示例如下:
function create_upload_video($vodClient) {
$request = new vod\CreateUploadVideoRequest();
$request->setTitle("視訊标題"); // 視訊标題(必填參數)
$request->setFileName("檔案名稱.mov"); // 視訊源檔案名稱,必須包含擴充名(必填參數)
$request->setDescription("視訊描述"); // 視訊源檔案描述(可選)
$request->setCoverURL("http://img.alicdn.com/tps/TB1qnJ1PVXXXXXCXXXXXXXXXXXX-700-700.png"); // 自定義視訊封面(可選)
$request->setTags("标簽1,标簽2"); // 視訊标簽,多個用逗号分隔(可選)
return $vodClient->getAcsResponse($request);
}
-
- 使用上傳憑證和位址初始化 OSS 用戶端(注意需要先 Base64 解碼并 Json Decode 再傳入)。示例如下:
function init_oss_client($uploadAuth, $uploadAddress) {
$ossClient = new OssClient($uploadAuth['AccessKeyId'], $uploadAuth['AccessKeySecret'], $uploadAddress['Endpoint'],
false, $uploadAuth['SecurityToken']);
$ossClient->setTimeout(86400*7); // 設定請求逾時時間,機關秒,預設是5184000秒, 建議不要設定太小,如果上傳檔案很大,消耗的時間會比較長
$ossClient->setConnectTimeout(10); // 設定連接配接逾時時間,機關秒,預設是10秒
return $ossClient;
}
-
- 說明 如果由于 SSL 配置異常導緻錯誤 (如出現 cURL error: SSL certificate problem), 可将 https 替換為 http 後再初始化 OssClient。
$uploadAddress['Endpoint'] = str_replace("https:", "http:", $uploadAddress['Endpoint']);
-
- 上傳本地檔案。示例如下:
function upload_local_file($ossClient, $uploadAddress, $localFile) {
return $ossClient->uploadFile($uploadAddress['Bucket'], $uploadAddress['FileName'], $localFile);
}
-
- 重新整理上傳憑證。示例如下:
function refresh_upload_video($vodClient, $videoId) {
$request = new vod\RefreshUploadVideoRequest();
$request->setVideoId($videoId);
return $vodClient->getAcsResponse($request);
}
- 執行完整流程(注意捕獲異常)。示例如下:
$accessKeyId = '<AccessKeyId>'; // 您的AccessKeyId
$accessKeySecret = '<AccessKeySecret>'; // 您的AccessKeySecret
$localFile = '/Users/yours/Video/testVideo.flv'; // 需要上傳到VOD的本地視訊檔案的完整路徑
try {
// 初始化VOD用戶端并擷取上傳位址和憑證
$vodClient = init_vod_client($accessKeyId, $accessKeySecret);
$createRes = create_upload_video($vodClient);
// 執行成功會傳回VideoId、UploadAddress和UploadAuth
$videoId = $createRes->VideoId;
$uploadAddress = json_decode(base64_decode($createRes->UploadAddress), true);
$uploadAuth = json_decode(base64_decode($createRes->UploadAuth), true);
// 使用UploadAuth和UploadAddress初始化OSS用戶端
$ossClient = init_oss_client($uploadAuth, $uploadAddress);
// 上傳檔案,注意是同步上傳會阻塞等待,耗時與檔案大小和網絡上行帶寬有關
//$result = upload_local_file($ossClient, $uploadAddress, $localFile);
$result = multipart_upload_file($ossClient, $uploadAddress, $localFile);
printf("Succeed, VideoId: %s", $videoId);
} catch (Exception $e) {
// var_dump($e);
printf("Failed, ErrorMessage: %s", $e->getMessage());
}
GO 上傳示例
支援 Go 1.7 及以上版本,可到 Go 官網 下載下傳合适的版本安裝。
- 使用 go get 安裝 SDK
go get -u github.com/aliyun/alibaba-cloud-sdk-go/sdk
- 說明
-
- 安裝過程中,界面不會列印提示,請耐心等待。如發生逾時,請再次執行指令。
- 當 GOPATH 對應的目錄下出現了子目錄 src/github.com/aliyun/alibaba-cloud-sdk-go/services/vod 即表示 SDK 安裝成功。
- 使用 glide 安裝 SDK
glide get github.com/aliyun/alibaba-cloud-sdk-go
func InitVodClient(accessKeyId string, accessKeySecret string) (client *vod.Client, err error) {
// 點播服務接入區域
regionId := "cn-shanghai"
// 建立授權對象
credential := &credentials.AccessKeyCredential{
accessKeyId,
accessKeySecret,
}
// 自定義config
config := sdk.NewConfig()
config.AutoRetry = true // 失敗是否自動重試
config.MaxRetryTime = 3 // 最大重試次數
config.Timeout = 3000000000 // 連接配接逾時,機關:納秒;預設為3秒
// 建立vodClient執行個體
return vod.NewClientWithOptions(regionId, config, credential)
}
func MyCreateUploadVideo(client *vod.Client) (response *vod.CreateUploadVideoResponse, err error) {
request := vod.CreateCreateUploadVideoRequest()
request.Title = "Sample Video Title"
request.Description = "Sample Description"
request.FileName = "/opt/video/sample/video_file.mp4"
//request.CateId = "-1"
request.CoverURL = "http://img.alicdn.com/tps/TB1qnJ1PVXXXXXCXXXXXXXXXXXX-700-700.png"
request.Tags = "tag1,tag2"
request.AcceptFormat = "JSON"
return client.CreateUploadVideo(request)
}
func InitOssClient(uploadAuthDTO UploadAuthDTO, uploadAddressDTO UploadAddressDTO) (*oss.Client, error) {
client, err := oss.New(uploadAddressDTO.Endpoint,
uploadAuthDTO.AccessKeyId,
uploadAuthDTO.AccessKeySecret,
oss.SecurityToken(uploadAuthDTO.SecurityToken),
oss.Timeout(86400*7, 86400*7))
return client, err
}
func UploadLocalFile(client *oss.Client, uploadAddressDTO UploadAddressDTO, localFile string) {
// 擷取存儲空間。
bucket, err := client.Bucket(uploadAddressDTO.Bucket)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
// 上傳本地檔案。
err = bucket.PutObjectFromFile(uploadAddressDTO.FileName, localFile)
if err != nil {
fmt.Println("Error:", err)
os.Exit(-1)
}
}
func MyRefreshUploadVideo(client *vod.Client) (response *vod.RefreshUploadVideoResponse, err error) {
request := vod.CreateRefreshUploadVideoRequest()
request.VideoId = ""
request.AcceptFormat = "JSON"
return client.RefreshUploadVideo(request)
}
type UploadAuthDTO struct {
AccessKeyId string
AccessKeySecret string
SecurityToken string
}
type UploadAddressDTO struct {
Endpoint string
Bucket string
FileName string
}
func main() {
var accessKeyId string = "<AccessKeyId>"; // 您的AccessKeyId
var accessKeySecret string = "<AccessKeySecret>"; // 您的AccessKeySecret
var localFile string = "/Users/yours/Video/testVideo.flv"; // 需要上傳到VOD的本地視訊檔案的完整路徑
// 初始化VOD用戶端并擷取上傳位址和憑證
var vodClient, initVodClientErr = InitVodClient(accessKeyId, accessKeySecret)
if initVodClientErr != nil {
fmt.Println("Error:", initVodClientErr)
return
}
// 擷取上傳位址和憑證
var response, createUploadVideoErr = MyCreateUploadVideo(vodClient)
if createUploadVideoErr != nil {
fmt.Println("Error:", createUploadVideoErr)
return
}
// 執行成功會傳回VideoId、UploadAddress和UploadAuth
var videoId = response.VideoId
var uploadAuthDTO UploadAuthDTO
var uploadAddressDTO UploadAddressDTO
var uploadAuthDecode, _ = base64.StdEncoding.DecodeString(response.UploadAuth)
var uploadAddressDecode, _ = base64.StdEncoding.DecodeString(response.UploadAddress)
json.Unmarshal(uploadAuthDecode, &uploadAuthDTO)
json.Unmarshal(uploadAddressDecode, &uploadAddressDTO)
// 使用UploadAuth和UploadAddress初始化OSS用戶端
var ossClient, _ = InitOssClient(uploadAuthDTO, uploadAddressDTO)
// 上傳檔案,注意是同步上傳會阻塞等待,耗時與檔案大小和網絡上行帶寬有關
UploadLocalFile(ossClient, uploadAddressDTO, localFile)
//MultipartUploadFile(ossClient, uploadAddressDTO, localFile)
fmt.Println("Succeed, VideoId:", videoId)
}
.NET 上傳示例
- .NET Framework 4.6.1 及其以上版本。
- .NET Standard 2.0 及其以上版本。
說明 更多資訊可參考
環境要求- NuGet 方式安裝在 解決方案資料總管面闆 中右擊您的項目選擇 管理 NuGet 程式包 菜單,在打開的 NuGet 管理面闆 中點選 浏覽 頁籤分别輸入 aliyun-net-sdk-core 和 aliyun-net-sdk-vod,選擇對應子產品最新版本點選 安裝 即可。
- .NET CLI 工具安裝。示例如下:
dotnet add package aliyun-net-sdk-core
dotnet add package aliyun-net-sdk-vod
- 說明 說明 更多資訊可參考 VOD .NET SDK 安裝 OSS .NET SDK 安裝
public static DefaultAcsClient InitVodClient(string accessKeyId, string accessKeySecret)
{
// 根據點播接入服務所在的Region填寫,例如:接入服務在上海,則填cn-shanghai
string regionId = "cn-shanghai";
IClientProfile profile = DefaultProfile.GetProfile(regionId, accessKeyId, accessKeySecret);
return new DefaultAcsClient(profile);
}
public static CreateUploadVideoResponse CreateUploadVideo(DefaultAcsClient vodClient)
{
CreateUploadVideoRequest request = new CreateUploadVideoRequest();
request.AcceptFormat = Aliyun.Acs.Core.Http.FormatType.JSON;
request.FileName = "vod_test.mp4";
request.Title = "this is title";
//request.Description = "this is desc";
//request.Tags = "tag1,tag2";
//request.CoverURL = "http://vod.aliyun.com/test_cover_url.jpg";
//request.CateId = -1;
//request.TemplateGroupId = "";
//request.WorkflowId = "";
//request.StorageLocation = "";
//request.AppId = "app-1000000";
//設定請求逾時時間
request.SetReadTimeoutInMilliSeconds(1000);
request.SetConnectTimeoutInMilliSeconds(1000);
return vodClient.GetAcsResponse(request);
}
public static OssClient InitOssClient(JObject uploadAuth, JObject uploadAddress)
{
string endpoint = uploadAddress.GetValue("Endpoint").ToString();
string accessKeyId = uploadAuth.GetValue("AccessKeyId").ToString();
string accessKeySecret = uploadAuth.GetValue("AccessKeySecret").ToString();
string securityToken = uploadAuth.GetValue("SecurityToken").ToString();
return new OssClient(endpoint, accessKeyId, accessKeySecret, securityToken);
}
public static void UploadLocalFile(OssClient ossClient, JObject uploadAddress, string localFile)
{
string bucketName = uploadAddress.GetValue("Bucket").ToString();
string objectName = uploadAddress.GetValue("FileName").ToString();
ossClient.PutObject(bucketName, objectName, localFile);
}
public static RefreshUploadVideoResponse RefreshUploadVideo(DefaultAcsClient vodClient)
{
RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
request.AcceptFormat = Aliyun.Acs.Core.Http.FormatType.JSON;
request.VideoId = "VideoId";
//設定請求逾時時間
request.SetReadTimeoutInMilliSeconds(1000);
request.SetConnectTimeoutInMilliSeconds(1000);
return vodClient.GetAcsResponse(request);
}
//您的AccessKeyId
string accessKeyId = "<Your AccessKeyId>";
//您的AccessKeySecret
string accessKeySecret = "<Your AccessKeySecret>";
//需要上傳到VOD的本地視訊檔案的完整路徑,需要包含檔案擴充名
string localFile = "/Users/yours/Video/testVideo.flv";
try {
// 初始化VOD用戶端并擷取上傳位址和憑證
DefaultAcsClient vodClient = InitVodClient(accessKeyId, accessKeySecret);
CreateUploadVideoResponse createUploadVideoResponse = CreateUploadVideo(vodClient);
// 執行成功會傳回VideoId、UploadAddress和UploadAuth
String videoId = createUploadVideoResponse.VideoId;
JObject uploadAuth = JObject.Parse(Base64Decode(createUploadVideoResponse.UploadAuth));
JObject uploadAddress = JObject.Parse(Base64Decode(createUploadVideoResponse.UploadAddress));
// 使用UploadAuth和UploadAddress初始化OSS用戶端
OssClient ossClient = InitOssClient(uploadAuth, uploadAddress);
// 上傳檔案,注意是同步上傳會阻塞等待,耗時與檔案大小和網絡上行帶寬有關
UploadLocalFile(ossClient, uploadAddress, localFile);
Console.WriteLine("Put local file succeed, VideoId : " + videoId);
}
catch (Exception e)
{
Console.WriteLine("Put local file fail, ErrorMessage : " + e.Message);
}
Java 上傳示例
- 環境要求使用 Java 1.8 及以上版本。
- 執行指令 java -version 可以檢視 Java 版本。
在 Maven 項目中加入依賴項在 Maven 工程中使用 OSS Java SDK,隻需在 pom.xml 中加入相應依賴即可。以 2.8.3 版本為例,在内加入如下内容:
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
VOD Java SDK OSS Java SDK public static DefaultAcsClient initVodClient(String accessKeyId, String accessKeySecret) throws ClientException {
// 根據點播接入服務所在的Region填寫,例如:接入服務在上海,則填cn-shanghai;其他區域請參見文檔[點播中心](~~98194~~)
String regionId = "cn-shanghai";
DefaultProfile profile = DefaultProfile.getProfile(regionId, accessKeyId, accessKeySecret);
DefaultAcsClient client = new DefaultAcsClient(profile);
return client;
}
public static CreateUploadVideoResponse createUploadVideo(DefaultAcsClient vodClient) {
CreateUploadVideoRequest request = new CreateUploadVideoRequest();
request.setFileName("vod_test.mp4");
request.setTitle("this is title");
//request.setDescription("this is desc");
//request.setTags("tag1,tag2");
//request.setCoverURL("http://vod.aliyun.com/test_cover_url.jpg");
//request.setCateId(-1L);
//request.setTemplateGroupId("");
//request.setWorkflowId("");
//request.setStorageLocation("");
//request.setAppId("app-1000000");
//設定請求逾時時間
request.setSysReadTimeout(1000);
request.setSysConnectTimeout(1000);
return vodClient.getAcsResponse(request);
}
public static OSSClient initOssClient(JSONObject uploadAuth, JSONObject uploadAddress) {
String endpoint = uploadAddress.getString("Endpoint");
String accessKeyId = uploadAuth.getString("AccessKeyId");
String accessKeySecret = uploadAuth.getString("AccessKeySecret");
String securityToken = uploadAuth.getString("SecurityToken");
return new OSSClient(endpoint, accessKeyId, accessKeySecret, securityToken);
}
public static void uploadLocalFile(OSSClient ossClient, JSONObject uploadAddress, String localFile){
String bucketName = uploadAddress.getString("Bucket");
String objectName = uploadAddress.getString("FileName");
File file = new File(localFile);
ossClient.putObject(bucketName, objectName, file);
}
public static RefreshUploadVideoResponse refreshUploadVideo(DefaultAcsClient vodClient) throws ClientException {
RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
request.setAcceptFormat(FormatType.JSON);
request.setVideoId("VideoId");
//設定請求逾時時間
request.setSysReadTimeout(1000);
request.setSysConnectTimeout(1000);
return vodClient.getAcsResponse(request);
}
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.FormatType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoRequest;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import org.apache.commons.codec.binary.Base64;
import java.io.File;
public class UploadDemo {
public static void main(String[] argv) {
//您的AccessKeyId
String accessKeyId = "<Your AccessKeyId>";
//您的AccessKeySecret
String accessKeySecret = "<Your AccessKeySecret>";
//需要上傳到VOD的本地視訊檔案的完整路徑,需要包含檔案擴充名
String localFile = "/Users/yours/Video/testVideo.flv";
try {
// 初始化VOD用戶端并擷取上傳位址和憑證
DefaultAcsClient vodClient = initVodClient(accessKeyId, accessKeySecret);
CreateUploadVideoResponse createUploadVideoResponse = createUploadVideo(vodClient);
// 執行成功會傳回VideoId、UploadAddress和UploadAuth
String videoId = createUploadVideoResponse.getVideoId();
JSONObject uploadAuth = JSONObject.parseObject(decodeBase64(createUploadVideoResponse.getUploadAuth()));
JSONObject uploadAddress = JSONObject.parseObject(decodeBase64(createUploadVideoResponse.getUploadAddress()));
// 使用UploadAuth和UploadAddress初始化OSS用戶端
OSSClient ossClient = initOssClient(uploadAuth, uploadAddress);
// 上傳檔案,注意是同步上傳會阻塞等待,耗時與檔案大小和網絡上行帶寬有關
uploadLocalFile(ossClient, uploadAddress, localFile);
System.out.println("Put local file succeed, VideoId : " + videoId);
} catch (Exception e) {
System.out.println("Put local file fail, ErrorMessage : " + e.getLocalizedMessage());
}
}
}
Demo 下載下傳
形式 | 源碼 | 更多參考資訊 |
PHP 上傳 Demo | PHP 版上傳 Demo 源碼 | OSS-PHP-SDK 上傳檔案 |
GO 上傳 Demo | GO 版上傳 Demo 源碼 | OSS-GO-SDK 上傳檔案 |
.NET 上傳 Demo | .NET 版上傳 Demo 源碼 | OSS-.NET-SDK 上傳檔案 |
Java 上傳 Demo | Java 版上傳 Demo 源碼 | OSS-Java-SDK 上傳檔案 |
說明 其它語言上傳 SDK 及 Demo 下載下傳請參見
上傳 SDK 下載下傳「視訊雲技術」你最值得關注的音視訊技術公衆号,每周推送來自阿裡雲一線的實踐技術文章,在這裡與音視訊領域一流工程師交流切磋。