Medya dosyalarını ApsaraVideo VOD'a yüklemek için JavaScript yükleme SDK'sını kullanın.
Tarayıcı gereksinimleri
Tarayıcı | Destekleniyor | Sürüm |
IE | ✔️ | Internet Explorer 10 ve sonrası |
Microsoft Edge | ✔️ | Tümü |
Chrome | ✔️ | Yaygın tarayıcı sürümleri |
Firefox | ✔️ | |
Safari | ✔️ | |
Android varsayılan tarayıcısı | ✔️ | |
iOS varsayılan tarayıcısı | ✔️ | |
Windows Phone varsayılan tarayıcısı | ✔️ |
Özellik açıklaması
JavaScript yükleme SDK'sı yalnızca ses, video ve görüntü yüklemelerini destekler. Yardımcı medya varlıkları desteklenmez.
SDK ve demo indirme
SDK sürümü: 1.5.7.
Güncelleme tarihi: 30 Ocak 2024.
İndirme adresleri: JavaScript için Yükleme SDK'sı V1.5.7 ve jQuery ve Vue için Demo kaynak kodu.
Entegrasyon yöntemleri
JavaScript yükleme SDK'sı, OSS SDK'sına bağımlıdır. window.OSS değerini geçerli bir şekilde ayarlayın. Aksi takdirde, ReferenceError: OSS is not defined hatası oluşur.
(Önerilen) HTML kodunda <script> kullanarak içe aktarma
<!-- es6-promise is required for Internet Explorer. Internet Explorer 10 and later are supported. -->
<script src="../lib/es6-promise.min.js"></script>
<script src="../lib/aliyun-oss-sdk-6.17.1.min.js"></script>
<script src="../aliyun-upload-sdk-1.5.7.min.js"></script>
Modül kullanarak içe aktarma
OSS modülünü manuel olarak window.OSS değerine atayın:
Dosyaları zaten <script> etiketleri aracılığıyla dahil ettiyseniz bu adımı atlayın.
import OSS from '../lib/aliyun-upload-sdk/lib/aliyun-oss-sdk-6.17.1.min'
window.OSS = OSS;
import '../lib/aliyun-upload-sdk/aliyun-upload-sdk-1.5.7.min'
Temel ayarlar
Yükleme örneğini başlatma
Yükleyiciyi tanımlamak için userId parametresini belirtin. Bir Alibaba Cloud hesap kimliğini veya Alibaba Cloud Account Center adresinden alınan özel bir kullanıcı kimliğini kullanın. userId değeri null ise veya belirtilmemişse hata oluşur.
regionparametresini desteklenen bir ApsaraVideo VOD bölge kimliğine ayarlayın. Daha fazla bilgi için bkz. ApsaraVideo VOD bölge kimlikleri.
var uploader = new AliyunUpload.Vod({
// Required. The identity of the uploader. The value can be an Alibaba Cloud account ID or a custom user ID. You can view the ID in Alibaba Cloud Account Center (https://account-console.alibabacloud.com/).
userId: "122",
// The regions where you want to upload the files. Default value: cn-shanghai.
// Examples: eu-central-1 and ap-southeast-1.
region: "",
// The size of each part in a multipart upload. Unit: bytes. The size cannot be smaller than 100 KB (100 × 1024). Default size: 1 MB (1 × 1024 × 1024).
partSize: 1048576,
// The maximum number of parts that can be uploaded in parallel. Default value: 5.
parallel: 5,
// The maximum number of times the system retries the upload when a network error occurs. Default value: 3.
retryCount: 3,
// The interval at which the system retries the upload when a network error occurs. Default value: 2. Unit: seconds.
retryDuration: 2,
// The upload is started.
onUploadstarted: function (uploadInfo) {},
// The upload is successful.
onUploadSucceed: function (uploadInfo) {},
// The upload fails.
onUploadFailed: function (uploadInfo, code, message) {},
// The upload progress. Unit: bytes.
onUploadProgress: function (uploadInfo, totalSize, loadedPercent) {},
// The upload credential or STS token expires.
onUploadTokenExpired: function (uploadInfo) {},
// All files are uploaded.
onUploadEnd: function (uploadInfo) {},
});
Kimlik bilgisini yapılandırma
Devam etmeden önce istemci yükleme sürecini anlayın ve bir yetkilendirme hizmeti dağıtın. Daha fazla bilgi için bkz. İstemcilerden yükleme.
Yöntem 1: Yükleme URL'si ve kimlik bilgisi kullanıyorsanız, yetkilendirme hizmetinden yükleme URL'lerini ve kimlik bilgilerini edinin.
Yöntem 2: STS belirteci kullanıyorsanız, yetkilendirme hizmetinden bir STS belirteci edinin. Daha fazla bilgi için bkz. STS belirteci alma.
Döndürülen yetkilendirme bilgilerini onUploadstarted geri aramasında yapılandırın. Kimlik bilgisi süresi dolduğunda onUploadTokenExpired geri araması tetiklenir. Yenileme işlemini çağırarak yeni bir kimlik bilgisi edinin.
Yöntem 1: Yükleme URL'si ve kimlik bilgisi
Yükleme URL'sini ve kimlik bilgisini yapılandırmak için setUploadAuthAndAddress öğesini çağırın. Kimlik bilgisi süresi dolduğunda onUploadTokenExpired geri araması tetiklenir. Yüklemeyi sürdürmek üzere yeni bir kimlik bilgisiyle resumeUploadWithAuth öğesini çağırın.
// The upload is started.
onUploadstarted: function (uploadInfo) {
let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
axios.get(refreshUrl).then(({data}) => {
let uploadAuth = data.UploadAuth
let uploadAddress = data.UploadAddress
let videoId = data.VideoId
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
})
},
// The upload credential expires.
onUploadTokenExpired: function (uploadInfo) {
// If the upload of a large file times out when you use Method 1 (UploadAuth),
// call the RefreshUploadVideo operation based on uploadInfo.videoId and re-obtain the value of UploadAuth.
// Then, call the resumeUploadWithAuth method. In this example, the value of UploadAuth is directly obtained because resumeUploadWithAuth is a test method.
let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
axios.get(refreshUrl).then(({data}) => {
let uploadAuth = data.UploadAuth
uploader.resumeUploadWithAuth(uploadAuth)
console.log('upload expired and resume upload with uploadauth ' + uploadAuth)
})
self.statusText = 'The upload times out...'
},
Yöntem açıklaması
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId)
uploader.resumeUploadWithAuth(uploadAuth)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Yöntem 2: STS belirteci
STS belirtecini yapılandırmak için setSTSToken öğesini çağırın. Belirteç süresi dolduğunda onUploadTokenExpired geri araması tetiklenir. Yüklemeyi sürdürmek üzere yeni bir belirteçle resumeUploadWithSTSToken öğesini çağırın.
/*Callback method - The upload is started.*/
onUploadstarted: function (uploadInfo) {
let stsUrl = "***.***.stsUrl" /*Use the setSTSToken method to obtain the STS token.*/
axios.get(stsUrl).then(({data}) => {
var info = data.SecurityTokenInfo
uploader.setSTSToken(uploadInfo, info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
})
},
/*Callback method - The credential times out.*/
onUploadTokenExpired: function (uploadInfo) {
let stsUrl = "***.***.stsUrl" /*Use the resumeUploadWithSTSToken method to refresh the STS token.*/
axios.get(stsUrl).then(({data}) => {
var info = data.SecurityTokenInfo
uploader.resumeUploadWithSTSToken(info.AccessKeyId, info.AccessKeySecret, info.SecretToken);
})
},
Yöntem açıklaması
uploader.setSTSToken(uploadInfo, accessKeyId, accessKeySecret, secretToken)
uploader.resumeUploadWithSTSToken(accessKeyId, accessKeySecret, secretToken)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Dosya ekleme
Dosyaları uploader listesine eklemek için <input type="file" /> üzerindeki change olayını dinleyin.
Native JavaScript
<form action="">
<input type="file" name="file" id="files" multiple/>
</form>
<script>
userData = '';
document.getElementById("files")
.addEventListener('change', function (event) {
for(var i=0; i<event.target.files.length; i++) {
// The logic code.
uploader.addFile(event.target.files[i],null,null,null,null)
}
});
</script>
Vue
<template>
<input type="file" id="fileUpload" @change="fileChange($event)">
</template>
<script>
export default {
data () {
return {
file: null,
}
},
methods: {
fileChange (e) {
this.file = e.target.files[0]
if (!this.file) {
alert("Select the files that you want to upload.")
return
}
var Title = this.file.name
var userData = '{"Vod":{}}'
if (this.uploader) {
this.uploader.stopUpload()
}
// Initialize an uploader.
this.uploader = this.createUploader()
this.uploader.addFile(this.file, null, null, null, userData)
},
}
}
</script>
Yöntem açıklaması
uploader.addFile(file,endpoint,bucket,object,paramData)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Başlık, açıklama, kod dönüştürme ve geri arama ayarları gibi dosya meta verileri. STS belirteci yüklemesi kullanırken
|
Yüklemeyi başlatma
uploader.startUpload();
Dosya yüklemesi başladıktan sonra, yükleme ilerlemesini senkronize etmek için
onUploadProgressgeri araması çağrılır.Dosya yüklemesi başarılı olursa, yükleme sonucunu döndürmek için
onUploadSucceedgeri araması çağrılır.
Yükleme ilerlemesini gösterme
// The file upload progress. Unit: bytes. You can use this function to obtain the upload progress and display the upload progress on the page.
onUploadProgress: function (uploadInfo, totalSize, progress) {
console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%")
let progressPercent = Math.ceil(progress * 100)
self.authProgress = progressPercent
self.statusText = 'The upload is ongoing...'
},
Yükleme sonucunu alma
// The upload is successful.
onUploadSucceed: function (uploadInfo) {
console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
self.statusText = 'The upload is successful!'
},
// The upload fails.
onUploadFailed: function (uploadInfo, code, message) {
console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message)
self.statusText = 'The upload fails!'
},
Bir video yüklendikten sonra, oynatma URL'sini almak için videoId değerini kullanın. Daha fazla bilgi için bkz. Oynatma kimlik bilgisi alma.
imageUrldeğeri görüntü yüklemeleri için otomatik olarak döndürülmez. Bu değeri almak için bir geri arama yapılandırın. Daha fazla bilgi için bkz. Geri aramaları yapılandırma.
Gelişmiş özellikler
Yükleme hızlandırmayı kullanma
Büyük dosyalar (GB/TB) veya Çin anakarasından Singapur bölgesi gibi bölgeler arası yüklemeler için yükleme hızlandırmayı etkinleştirin.
Yükleme hızlandırma işlevini etkinleştirmek için bir destek talebi göndermeniz gerekir. Alibaba Cloud hesap UID'sini ve yükleme hızlandırma kullanması gereken depolama adresini sağlamanız gerekmektedir.
Yöntem 1: Yükleme URL'si ve kimlik bilgisi
CreateUploadVideo işlemini çağırın ve UserData parametresinde hızlandırmayı yapılandırın:
UserData={
"AccelerateConfig": {
"Type": "oss",
"Domain": "https://oss-accelerate.aliyuncs.com"
}
}
Yöntem 2: STS belirteci
parmData parametresindeki UserData özelliğiyle addFile yöntemini çağırın:
uploader.addFile(file,null,null,null,'{"Vod":{"UserData":{"AccelerateConfig":{"Type":"oss","Domain":"https://oss-accelerate.aliyuncs.com"}}}}');
UserData açıklaması
|
|
|
|
|
|
|
|
|
|
Aşağıdaki tabloda parametreler açıklanmaktadır.
Parametre | Tür | Açıklama |
Type | string | Yükleme hızlandırma türü. oss olarak ayarlayın. |
Domain | string | Hızlandırılmış alan adı. Varsayılan olarak HTTPS. Not Yükleme hızlandırmayı etkinleştirdikten sonra atanan bir hızlandırılmış uç nokta kullanılır, örneğin vod-***.oss-accelerate.aliyuncs.com. |
UserData nasıl yapılandırılacağı hakkında daha fazla bilgi için bkz. İstek parametresi açıklamaları.
Yüklemeyi durdurma
stopUpload yalnızca bir dosya yüklenirken etkili olur.
uploader.stopUpload();
Dosya listesini yönetme
Yüklenen veya devam eden dosyaları yönetmek için aşağıdaki işlemleri kullanın.
-
listFiles: Yükleme listesini sorgular.
addFile aracılığıyla eklenen dosyaları döndürür. file özelliği dosya türünü belirtir. Yönetim işlemleri için dosya dizinlerini almak üzere listeyi yineleyin.
var list = uploader.listFiles(); for (var i=0; i<list.length; i++) { console.log("file:" + list[i].file.name); } -
deleteFile: Yüklenecek bir dosyayı kaldırır.
uploader.deleteFile(index);//The index of the file that you want to delete. The index is returned by the listFiles operation. -
cancelFile: Bir dosyanın yüklemesini iptal eder.
NotcancelFileöğesini çağırdıktan sonra konsoldaoss is cancel as errormesajı görünür. Bu, yüklenen parçaların depolama alanını kaplamasını ve maliyet oluşturmasını önler.İptal edilen bir yüklemeyi sürdürmek için önce dosyayı geri yüklemek amacıyla
uploader.resumeFile(index);öğesini çağırın.
uploader.cancelFile(index); -
resumeFile: Bir dosyanın yüklemesini sürdürür.
uploader.resumeFile(index); -
cleanList: Yükleme listesini temizler.
uploader.cleanList();
Kaldığı yerden devam eden yükleme
Bir sayfa çökmesi veya tarayıcı hatası nedeniyle yükleme başarısız olursa, SDK yeniden yüklemede kaldığı yerden devam eder ve kimlik bilgisini onUploadstarted geri aramasından alır. Yöntem 1: Yükleme URL'si ve kimlik bilgisi ile videoId kullanarak ApsaraVideo VOD API işlemlerini çağırın ve kırılma noktası bilgilerini alın:
// The upload is started.
onUploadstarted: function (uploadInfo) {
// If you use UploadAuth to upload the file, call the uploader.setUploadAuthAndAddress method.
// If you use UploadAuth to upload the file, call different ApsaraVideo VOD API operations to obtain uploadAuth and uploadAddress based on whether uploadInfo.videoId has a value.
// If uploadInfo.videoId has a value, call the RefreshUploadVideo operation. Otherwise, call the CreateUploadVideo operation.
// Take note of the following information: An operation is directly called to obtain UploadAuth because this is a test demo. In actual scenarios, you must call a specific operation to obtain UploadAuth based on whether uploadInfo.videoId has a value.
// If uploadInfo.videoId has a value, call the RefreshUploadVideo operation.
// If uploadInfo.videoId is empty, call the CreateUploadVideo operation.
if (!uploadInfo.videoId) {
let createUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/CreateUploadVideo?Title=testvod1&FileName=aa.mp4&BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&VideoId=5bfcc7864fc14b96972842172207c9e6'
axios.get(createUrl).then(({data}) => {
let uploadAuth = data.UploadAuth
let uploadAddress = data.UploadAddress
let videoId = data.VideoId
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
})
self.statusText = 'The file upload is started...'
console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object)
} else {
// Display the breakpoint information.
console.log(uploader.getCheckpoint(uploadInfo.file));
// If the videoId parameter has a value, the video upload fails. The system resumes the upload from the breakpoint. You must refresh the upload credential based on the value of videoId.
let refreshUrl = 'https://demo-vod.cn-shanghai.aliyuncs.com/voddemo/RefreshUploadVideo?BusinessType=vodai&TerminalType=pc&DeviceModel=iPhone9,2&UUID=59ECA-4193-4695-94DD-7E1247288&AppVersion=1.0.0&Title=haha1&FileName=xxx.mp4&VideoId=' + uploadInfo.videoId
axios.get(refreshUrl).then(({data}) => {
let uploadAuth = data.UploadAuth
let uploadAddress = data.UploadAddress
let videoId = data.VideoId
uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)
})
}
}
Kırılma noktası bilgilerini alma:
uploader.getCheckpoint(file);
Özel durum işleme
Bir özel durum oluşursa, nedeni bulmak için Hata kodları konusundaki istemci yükleme SDK'sı bölümünü kontrol edin.