前端参考官方示例(jQuery版)
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>阿里云 JavaScript上传SDK Demo (使用jquery)</title><script src="__STATIC__/jquery.min.js"></script><script src="__STATIC__/aliyun-upload-sdk/aliyun-upload-sdk-1.5.6.min.js"></script><script src="__STATIC__/aliyun-upload-sdk/lib/es6-promise.min.js"></script><script src="__STATIC__/aliyun-upload-sdk/lib/aliyun-oss-sdk-6.17.1.min.js"></script><style type="text/css">.container {width: 1200px;margin: 0 auto;}.input-control {margin: 5px 0;}.input-control label {font-size: 14px;color: #333;width: 30%;text-align: right;display: inline-block;vertical-align: middle;margin-right: 10px;}.input-control input {width: 30%;height: 30px;padding: 0 5px;}.upload {padding: 30px 50px;}.progress {font-size: 14px;}.progress i {font-style: normal;}.upload-type {color: #666;font-size: 12px;padding: 10px 0;}.upload-type button {margin: 0 10px 0 20px;}.status {font-size: 14px;margin-left: 30px;}.info {font-size: 14px;padding-left: 30px;}</style>
</head>
<body><div class="container"><div class="upload"><div><input type="file" id="fileUpload"><label class="status">上传状态: <span id="status"></span></label></div><div class="upload-type">上传方式一, 使用 UploadAuth 上传:<button id="authUpload" disabled="true">开始上传</button><button id="pauseUpload" disabled="true">暂停</button><button id="resumeUpload" disabled="true">恢复上传</button><span class="progress">上传进度: <i id="auth-progress">0</i> %</span><span></span></div></div><div class="info">uploadAuth及uploadAddress参数请查看<a href="https://help.aliyun.com/document_detail/55407.html" target="_blank">获取上传地址和凭证 </a></div></div><script>//兼容IE11if (!FileReader.prototype.readAsBinaryString) {FileReader.prototype.readAsBinaryString = function (fileData) {var binary = "";var pt = this;var reader = new FileReader(); reader.onload = function (e) {var bytes = new Uint8Array(reader.result);var length = bytes.byteLength;for (var i = 0; i < length; i++) {binary += String.fromCharCode(bytes[i]);}//pt.result - readonly so assign binarypt.content = binary;pt.onload();}reader.readAsArrayBuffer(fileData);}}$(document).ready(function () {/** * 创建一个上传对象* 使用 UploadAuth 上传方式*/function createUploader () {var uploader = new AliyunUpload.Vod({timeout: 60000,partSize: 1048576,parallel: 5,retryCount: 3,retryDuration: 2,region: 'cn-shanghai',userId: '', // 输入用户id;localCheckpoint: true, //此参数是禁用服务端缓存// 添加文件成功addFileSuccess: function (uploadInfo) {console.log('addFileSuccess');$('#authUpload').attr('disabled', false);$('#resumeUpload').attr('disabled', false);$('#status').text('添加文件成功, 等待上传...');console.log("addFileSuccess: " + uploadInfo.file.name);},// 开始上传onUploadstarted: function (uploadInfo) {// 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法// 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值,调用点播的不同接口获取uploadauth和uploadAddress// 如果 uploadInfo.videoId 有值,调用刷新视频上传凭证接口,否则调用创建视频上传凭证接口// 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi// 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)// 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)if (!uploadInfo.videoId) {var createUrl = '/index/demo/createVideo/'; // index应用\demo控制器\createVideo方法$.get(createUrl, function (data) {var uploadAuth = data.uploadAuth;var uploadAddress = data.uploadAddress;var videoId = data.videoId;console.log(videoId);uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress,videoId)}, 'json');$('#status').text('文件开始上传...');console.log("onUploadStarted:" + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);} else {// 如果videoId有值,根据videoId刷新上传凭证// https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcYvar refreshUrl = '/index/demo/refreshVideo?videoId=' + uploadInfo.videoId;$.get(refreshUrl, function (data) {var uploadAuth = data.uploadAuth;var uploadAddress = data.uploadAddress;var videoId = data.videoId;uploader.setUploadAuthAndAddress(uploadInfo, uploadAuth, uploadAddress, videoId);}, 'json');}},// 文件上传成功onUploadSucceed: function (uploadInfo) {console.log("onUploadSucceed: " + uploadInfo.file.name + ", endpoint:" + uploadInfo.endpoint + ", bucket:" + uploadInfo.bucket + ", object:" + uploadInfo.object);$('#status').text('文件上传成功!');},// 文件上传失败onUploadFailed: function (uploadInfo, code, message) {console.log("onUploadFailed: file:" + uploadInfo.file.name + ",code:" + code + ", message:" + message);$('#status').text('文件上传失败!');},// 取消文件上传onUploadCanceled: function (uploadInfo, code, message) {console.log("Canceled file: " + uploadInfo.file.name + ", code: " + code + ", message:" + message);$('#status').text('文件上传已暂停!');},// 文件上传进度,单位:字节, 可以在这个函数中拿到上传进度并显示在页面上onUploadProgress: function (uploadInfo, totalSize, progress) {console.log("onUploadProgress:file:" + uploadInfo.file.name + ", fileSize:" + totalSize + ", percent:" + Math.ceil(progress * 100) + "%");var progressPercent = Math.ceil(progress * 100);$('#auth-progress').text(progressPercent);$('#status').text('文件上传中...');},// 上传凭证超时onUploadTokenExpired: function (uploadInfo) {// 上传大文件超时, 如果是上传方式一即根据 UploadAuth 上传时// 需要根据 uploadInfo.videoId 调用刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)重新获取 UploadAuth// 然后调用 resumeUploadWithAuth 方法, 这里是测试接口, 所以我直接获取了 UploadAuth$('#status').text('文件上传超时!');let refreshUrl = '/index/demo/refreshVideo?videoId=' + uploadInfo.videoId;$.get(refreshUrl, function (data) {var uploadAuth = data.uploadAuth;uploader.resumeUploadWithAuth(uploadAuth);console.log('upload expired and resume upload with uploadauth ' + uploadAuth);}, 'json');},// 全部文件上传结束onUploadEnd: function (uploadInfo) {$('#status').text('文件上传完毕!');console.log("onUploadEnd: uploaded all the files");}})return uploader;}var uploader = null;$('#fileUpload').on('change', function (e) {var file = e.target.files[0];if (!file) {alert("请先选择需要上传的文件!");return;}var Title = file.name;var userData = '{"Vod":{}}';if (uploader) {uploader.stopUpload();$('#auth-progress').text('0');$('#status').text("");}uploader = createUploader();// 首先调用 uploader.addFile(event.target.files[i], null, null, null, userData)console.log(uploader);uploader.addFile(file, null, null, null, userData);$('#authUpload').attr('disabled', false);$('#pauseUpload').attr('disabled', true);$('#resumeUpload').attr('disabled', true);});// 第一种方式 UploadAuth 上传 $('#authUpload').on('click', function () {// 然后调用 startUpload 方法, 开始上传if (uploader !== null) {uploader.startUpload();$('#authUpload').attr('disabled', true);$('#pauseUpload').attr('disabled', false);}});// 暂停上传$('#pauseUpload').on('click', function () {if (uploader !== null) {uploader.stopUpload();$('#resumeUpload').attr('disabled', false);$('#pauseUpload').attr('disabled', true);}});$('#resumeUpload').on('click', function () {if (uploader !== null) {uploader.startUpload();$('#resumeUpload').attr('disabled', true);$('#pauseUpload').attr('disabled', false);}});});</script>
</body>
</html>
前提条件:阿里云镜像
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
安装sdk:
composer require alibabacloud/vod-20170321
后端代码:(tp8)
use AlibabaCloud\SDK\Vod\V20170321\Vod;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Vod\V20170321\Models\CreateUploadVideoRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Vod\V20170321\Models\RefreshUploadVideoRequest;class Demo
{/*** 使用AK&SK初始化账号Client* @return Vod Client*/public static function createClient(){$config = new Config(["accessKeyId" => '', // 从官方获取"accessKeySecret" => '']);$config->endpoint = "vod.cn-shanghai.aliyuncs.com";return new Vod($config);}/*** 获取上传视频地址和凭证;* @return Json*/public function createVideo(){$client = self::createClient();$createUploadVideoRequest = new CreateUploadVideoRequest(["fileName" => "D:\video_01.mp4","title" => "UploadTest"]);$runtime = new RuntimeOptions([]);try {// 复制代码运行请自行打印 API 的返回值$result = $client->createUploadVideoWithOptions($createUploadVideoRequest, $runtime);$uploadAuth = $result->body->uploadAuth;$videoId = $result->body->videoId;$uploadAddress = $result->body->uploadAddress;// 构建返回的数组$data = ['uploadAuth' => $uploadAuth,'videoId' => $videoId,'uploadAddress' => $uploadAddress,];return json($data);}catch (Exception $error) {if (!($error instanceof TeaError)) {$error = new TeaError([], $error->getMessage(), $error->getCode(), $error);}$res = Utils::assertAsString($error->message);return json(['code'=>500,'msg'=>$res]);}}/*** 刷新视频上传凭证;*/public function refreshVideo(){$client = self::createClient();$videoId = input('get.videoId');// dd($videoId);$refreshUploadVideoRequest = new RefreshUploadVideoRequest(["videoId" => $videoId]);$runtime = new RuntimeOptions([]);try {// 复制代码运行请自行打印 API 的返回值$result = $client->refreshUploadVideoWithOptions($refreshUploadVideoRequest, $runtime);$uploadAuth = $result->body->uploadAuth;$videoId = $result->body->videoId;$uploadAddress = $result->body->uploadAddress;// 构建返回的数组$data = ['uploadAuth' => $uploadAuth,'videoId' => $videoId,'uploadAddress' => $uploadAddress,];return json($data);}catch (Exception $error) {if (!($error instanceof TeaError)) {$error = new TeaError([], $error->getMessage(), $error->getCode(), $error);}$res = Utils::assertAsString($error->message);return json(['code'=>500,'msg'=>$res]);}}/*** 获取视频播放地址;*/public function getPlayUrl(){$client = self::createClient();$getPlayInfoRequest = new GetPlayInfoRequest(["videoId" => "c0bb1237eb8f71ef92585017f0e80102"]);$runtime = new RuntimeOptions([]);try {// 复制代码运行请自行打印 API 的返回值$result = $client->getPlayInfoWithOptions($getPlayInfoRequest, $runtime);// dd($result);$playUrl = $result->body->playInfoList->playInfo[0]->playURL;return json(['code'=>200,'msg'=>'success','data'=>$playUrl]);}catch (Exception $error) {if (!($error instanceof TeaError)) {$error = new TeaError([], $error->getMessage(), $error->getCode(), $error);}$res = Utils::assertAsString($error->message);return json(['code'=>500,'msg'=>$res]);}}
}
前端播放视频:(参考官方文档)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="IE=edge" >
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no"/>
<title>Aliplayer Online Settings</title>
<link rel="stylesheet" href="https://g.alicdn.com/apsara-media-box/imp-web-player/2.29.1/skins/default/aliplayer-min.css" />
<script type="text/javascript" charset="utf-8" src="https://g.alicdn.com/apsara-media-box/imp-web-player/2.29.1/aliplayer-min.js"></script>
</head>
<body>
<div class="prism-player" id="player-con"></div>
<script>
var player = new Aliplayer({"id": "player-con","source": "https://www.sqhsy.cn/sv/66ede8da-1950958f8ee/66ede8da-1950958f8ee.mp4","width": "100%","height": "500px","autoplay": true,"isLive": false,"rePlay": false,"videoHeight": undefined,"isVBR": undefined,"preload": true,"controlBarVisibility": "hover","useH5Prism": true
}, function (player) {console.log("The player is created");}
);
</script>
</body>
测试环境:debian 12; php 8.3; thinkphp8.1 欢迎大佬们纠正