Commit 06140e29 authored by liuyang's avatar liuyang

update

parent dfe2b2e4
...@@ -40,7 +40,6 @@ ...@@ -40,7 +40,6 @@
<docker.plugin.version>1.1.1</docker.plugin.version> <docker.plugin.version>1.1.1</docker.plugin.version>
<baidu.aip.version>4.11.3</baidu.aip.version> <baidu.aip.version>4.11.3</baidu.aip.version>
<shiro.version>1.4.0</shiro.version> <shiro.version>1.4.0</shiro.version>
<fastjson.version>1.2.60</fastjson.version>
<weixin-java.version>3.6.0</weixin-java.version> <weixin-java.version>3.6.0</weixin-java.version>
<hutool.version>5.3.5</hutool.version> <hutool.version>5.3.5</hutool.version>
</properties> </properties>
...@@ -280,6 +279,16 @@ ...@@ -280,6 +279,16 @@
<artifactId>aliyun-sdk-oss</artifactId> <artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version> <version>3.10.2</version>
</dependency> </dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-core</artifactId>
<version>4.5.1</version>
</dependency>
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>aliyun-java-sdk-vod</artifactId>
<version>2.15.11</version>
</dependency>
</dependencies> </dependencies>
......
...@@ -11,8 +11,13 @@ public class AliyunConfig { ...@@ -11,8 +11,13 @@ public class AliyunConfig {
private String accessKeyId; private String accessKeyId;
@Value("${aliyun.accessKeySecret}") @Value("${aliyun.accessKeySecret}")
private String accessKeySecret; private String accessKeySecret;
@Value("${aliyun.userId}")
private String userId;
@Value("${aliyun.oss.endpoint}") @Value("${aliyun.oss.endpoint}")
private String endpoint; private String endpoint;
@Value("${aliyun.oss.bucket}") @Value("${aliyun.oss.bucket}")
private String bucket; private String bucket;
@Value("${aliyun.vod.region}")
private String region;
} }
package com.qkdata.biz.aliyun.controller; package com.qkdata.biz.aliyun.controller;
import com.aliyuncs.vod.model.v20170321.CreateUploadVideoResponse;
import com.aliyuncs.vod.model.v20170321.RefreshUploadVideoResponse;
import com.qkdata.biz.aliyun.service.AliyunService; import com.qkdata.biz.aliyun.service.AliyunService;
import com.qkdata.biz.aliyun.vo.AliyunOSSUploadPolicyModel; import com.qkdata.biz.aliyun.vo.AliyunOSSUploadPolicyModel;
import com.qkdata.common.base.model.Result; import com.qkdata.common.base.model.Result;
...@@ -8,9 +10,11 @@ import io.swagger.annotations.ApiOperation; ...@@ -8,9 +10,11 @@ import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.util.Map;
@Api(tags = "阿里云API") @Api(tags = "阿里云API")
@RestController @RestController
...@@ -19,10 +23,27 @@ public class AliyunApiController { ...@@ -19,10 +23,27 @@ public class AliyunApiController {
@Autowired @Autowired
private AliyunService aliyunService; private AliyunService aliyunService;
@ApiOperation("获取阿里云视视频上传所需配置信息")
@GetMapping("/videoConfig")
public Result<Map<String, String>> videoConfig() {
return Result.succeed(aliyunService.getVideoConfig());
}
@ApiOperation("获取阿里云OSS上传所需要的参数") @ApiOperation("获取阿里云OSS上传所需要的参数")
@GetMapping("/uploadPolicy") @GetMapping("/uploadPolicy")
public Result<AliyunOSSUploadPolicyModel> getUploadPolicy() throws UnsupportedEncodingException { public Result<AliyunOSSUploadPolicyModel> getUploadPolicy() throws UnsupportedEncodingException {
return Result.succeed(aliyunService.getUploadPolicy()); return Result.succeed(aliyunService.getUploadPolicy());
} }
@ApiOperation("获取阿里云视频上传所需要的参数")
@GetMapping("/videoUploadPolicy")
public Result<CreateUploadVideoResponse> videoUploadPolicy(@RequestParam(required = true) String title, @RequestParam(required = true) String fileName) throws Exception {
return Result.succeed(aliyunService.createUploadVideo(title,fileName));
}
@ApiOperation("刷新阿里云视频上传所需要的参数")
@GetMapping("/refreshVideoUploadPolicy")
public Result<RefreshUploadVideoResponse> refreshVideoUploadPolicy(@RequestParam(required = true) String videoId) throws Exception {
return Result.succeed(aliyunService.refreshUploadVideo(videoId));
}
} }
package com.qkdata.biz.aliyun.controller; package com.qkdata.biz.aliyun.controller;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.JSONObject;
import com.qkdata.biz.aliyun.service.AliyunService; import com.qkdata.biz.aliyun.service.AliyunService;
import com.qkdata.biz.aliyun.vo.AliyunCallbackRespModel; import com.qkdata.biz.aliyun.vo.AliyunCallbackRespModel;
import com.qkdata.biz.aliyun.vo.AliyunVideoCallbackModel;
import com.qkdata.biz.aliyun.vo.ExtendData;
import com.qkdata.biz.management.entity.ResourcePO; import com.qkdata.biz.management.entity.ResourcePO;
import com.qkdata.biz.management.service.ResourceService; import com.qkdata.biz.management.service.ResourceService;
import com.qkdata.common.annotation.SysLog; import com.qkdata.common.annotation.SysLog;
...@@ -19,7 +22,7 @@ import org.springframework.web.bind.annotation.RestController; ...@@ -19,7 +22,7 @@ import org.springframework.web.bind.annotation.RestController;
@Api(tags = "阿里云OSS callback") @Api(tags = "阿里云OSS callback")
@RestController @RestController
@RequestMapping("/aliyun") @RequestMapping("/aliyun")
public class AliyunOSSCallbackController { public class AliyunCallbackController {
@Autowired @Autowired
private AliyunService aliyunService; private AliyunService aliyunService;
...@@ -38,6 +41,19 @@ public class AliyunOSSCallbackController { ...@@ -38,6 +41,19 @@ public class AliyunOSSCallbackController {
data.put("url",aliyunService.generateUrl(model.getFileName())); data.put("url",aliyunService.generateUrl(model.getFileName()));
return Result.succeed(data); return Result.succeed(data);
} }
@SysLog("video上传回调")
@PostMapping("/video/callback")
public Result<String> videoCallback(@RequestBody String data){
log.info(data);
AliyunVideoCallbackModel model = JSONObject.parseObject(data,AliyunVideoCallbackModel.class);
String videoId = model.getVideoId();
String extendStr = model.getExtend();
if (StrUtil.isNotBlank(extendStr)){
ExtendData extendData = JSONObject.parseObject(extendStr,ExtendData.class);
String fileName = extendData.getFileName();
}
return Result.succeed("ok");
}
private Long saveToResource(AliyunCallbackRespModel model) { private Long saveToResource(AliyunCallbackRespModel model) {
ResourcePO po = new ResourcePO(); ResourcePO po = new ResourcePO();
......
...@@ -6,6 +6,13 @@ import com.aliyun.oss.OSSClientBuilder; ...@@ -6,6 +6,13 @@ import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil; import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode; import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions; import com.aliyun.oss.model.PolicyConditions;
import com.aliyuncs.DefaultAcsClient;
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 com.google.common.collect.Maps;
import com.qkdata.biz.aliyun.config.AliyunConfig; import com.qkdata.biz.aliyun.config.AliyunConfig;
import com.qkdata.biz.aliyun.vo.AliyunOSSUploadPolicyModel; import com.qkdata.biz.aliyun.vo.AliyunOSSUploadPolicyModel;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -16,6 +23,7 @@ import javax.annotation.PostConstruct; ...@@ -16,6 +23,7 @@ import javax.annotation.PostConstruct;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.net.URL; import java.net.URL;
import java.util.Date; import java.util.Date;
import java.util.Map;
@Service @Service
public class AliyunService { public class AliyunService {
...@@ -26,6 +34,7 @@ public class AliyunService { ...@@ -26,6 +34,7 @@ public class AliyunService {
@Value("${server.servlet.context-path}") @Value("${server.servlet.context-path}")
private String serverContextPath; private String serverContextPath;
private OSS ossClient; private OSS ossClient;
private DefaultAcsClient vodClient;
/** /**
* 过期时间(秒) * 过期时间(秒)
*/ */
...@@ -36,6 +45,15 @@ public class AliyunService { ...@@ -36,6 +45,15 @@ public class AliyunService {
if (ossClient == null){ if (ossClient == null){
ossClient = new OSSClientBuilder().build(aliyunConfig.getEndpoint(),aliyunConfig.getAccessKeyId(),aliyunConfig.getAccessKeySecret()); ossClient = new OSSClientBuilder().build(aliyunConfig.getEndpoint(),aliyunConfig.getAccessKeyId(),aliyunConfig.getAccessKeySecret());
} }
if (vodClient == null){
vodClient = initVodClient();
}
}
private DefaultAcsClient initVodClient() {
DefaultProfile profile = DefaultProfile.getProfile(aliyunConfig.getRegion(),aliyunConfig.getAccessKeyId(),aliyunConfig.getAccessKeySecret());
DefaultAcsClient client = new DefaultAcsClient(profile);
return client;
} }
public AliyunOSSUploadPolicyModel getUploadPolicy() throws UnsupportedEncodingException { public AliyunOSSUploadPolicyModel getUploadPolicy() throws UnsupportedEncodingException {
...@@ -74,4 +92,51 @@ public class AliyunService { ...@@ -74,4 +92,51 @@ public class AliyunService {
URL url = ossClient.generatePresignedUrl(aliyunConfig.getBucket(), fileName, expiration); URL url = ossClient.generatePresignedUrl(aliyunConfig.getBucket(), fileName, expiration);
return url.toString(); return url.toString();
} }
/**
* 获取视频上传地址和凭证
* @return CreateUploadVideoResponse 获取视频上传地址和凭证响应数据
* @throws Exception
*/
public CreateUploadVideoResponse createUploadVideo(String title,String fileName) throws Exception {
CreateUploadVideoRequest request = new CreateUploadVideoRequest();
request.setTitle(title);
request.setFileName(fileName);
//UserData,用户自定义设置参数,用户需要单独回调URL及数据透传时设置(非必须)
JSONObject userData = new JSONObject();
//UserData回调部分设置
JSONObject messageCallback = new JSONObject();
messageCallback.put("CallbackURL", frontendDomain + serverContextPath + "/aliyun/video/callback");
messageCallback.put("CallbackType", "http");
userData.put("MessageCallback", messageCallback.toJSONString());
//UserData透传数据部分设置
JSONObject extend = new JSONObject();
extend.put("fileName", fileName);
userData.put("Extend", extend.toJSONString());
request.setUserData(userData.toJSONString());
return vodClient.getAcsResponse(request);
}
/**
* 刷新视频上传凭证
* @param videoId
* @return RefreshUploadVideoResponse 刷新视频上传凭证响应数据
* @throws Exception
*/
public RefreshUploadVideoResponse refreshUploadVideo(String videoId) throws Exception {
RefreshUploadVideoRequest request = new RefreshUploadVideoRequest();
request.setVideoId(videoId);
return vodClient.getAcsResponse(request);
}
public Map<String,String> getVideoConfig() {
Map<String,String> map = Maps.newConcurrentMap();
map.put("userId",aliyunConfig.getUserId());
map.put("region",aliyunConfig.getRegion());
return map;
}
} }
package com.qkdata.biz.aliyun.vo;
import lombok.Data;
@Data
public class AliyunVideoCallbackModel {
private String Status;
private String FileUrl;
private String VideoId;
private String EventType;
private String Extend;
private String EventTime;
private Long Size;
}
package com.qkdata.biz.aliyun.vo;
import lombok.Data;
@Data
public class ExtendData {
private String fileName;
}
...@@ -89,6 +89,8 @@ jwt: ...@@ -89,6 +89,8 @@ jwt:
- /api/wx/user/** - /api/wx/user/**
- /api/sys/login - /api/sys/login
- /api/aliyun/mgr/uploadPolicy #test - /api/aliyun/mgr/uploadPolicy #test
- /api/aliyun/mgr/videoUploadPolicy #test
- /api/aliyun/mgr/videoConfig #test
aud: qkdata aud: qkdata
exp: 720 #24*30 30天 exp: 720 #24*30 30天
...@@ -106,6 +108,9 @@ sms: ...@@ -106,6 +108,9 @@ sms:
aliyun: aliyun:
accessKeyId: LTAI4GCTRFRxud86a58AoV3X accessKeyId: LTAI4GCTRFRxud86a58AoV3X
accessKeySecret: Rpwj9DBwJpNWzwjcFeffLWqEuJ56i0 accessKeySecret: Rpwj9DBwJpNWzwjcFeffLWqEuJ56i0
userId: 1338241234116556
oss: oss:
endpoint: oss-cn-beijing.aliyuncs.com endpoint: oss-cn-beijing.aliyuncs.com
bucket: qkdata-online-edu bucket: qkdata-online-edu
vod:
region: cn-shanghai
\ No newline at end of file
...@@ -44,7 +44,27 @@ ...@@ -44,7 +44,27 @@
<p>&nbsp;</p> <p>&nbsp;</p>
<h2>视频上传示例</h2>
<div>
<form action="">
<input type="file" name="file" id="files" multiple/>
</form>
</div>
</body> </body>
<script type="text/javascript" src="lib/plupload-2.1.2/js/plupload.full.min.js"></script> <script type="text/javascript" src="lib/plupload-2.1.2/js/plupload.full.min.js"></script>
<script type="text/javascript" src="upload.js"></script> <script type="text/javascript" src="upload.js"></script>
<script src="../lib/es6-promise.min.js"></script>
<script src="../lib/aliyun-oss-sdk6.10.0.min.js"></script>
<script src="../aliyun-vod-upload-sdk1.5.2.min.js"></script>
<script type="text/javascript">
userData = '';
document.getElementById("files")
.addEventListener('change', function (event) {
for(var i=0; i<event.target.files.length; i++) {
//逻辑代码
}
});
</script>
</html> </html>
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.ES6Promise=e()}(this,function(){"use strict";function t(t){var e=typeof t;return null!==t&&("object"===e||"function"===e)}function e(t){return"function"==typeof t}function n(t){I=t}function r(t){J=t}function o(){return function(){return process.nextTick(a)}}function i(){return"undefined"!=typeof H?function(){H(a)}:c()}function s(){var t=0,e=new V(a),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){return t.port2.postMessage(0)}}function c(){var t=setTimeout;return function(){return t(a,1)}}function a(){for(var t=0;t<G;t+=2){var e=$[t],n=$[t+1];e(n),$[t]=void 0,$[t+1]=void 0}G=0}function f(){try{var t=require,e=t("vertx");return H=e.runOnLoop||e.runOnContext,i()}catch(n){return c()}}function l(t,e){var n=arguments,r=this,o=new this.constructor(p);void 0===o[et]&&k(o);var i=r._state;return i?!function(){var t=n[i-1];J(function(){return x(i,o,t,r._result)})}():E(r,o,t,e),o}function h(t){var e=this;if(t&&"object"==typeof t&&t.constructor===e)return t;var n=new e(p);return g(n,t),n}function p(){}function v(){return new TypeError("You cannot resolve a promise with itself")}function d(){return new TypeError("A promises callback cannot return that same promise.")}function _(t){try{return t.then}catch(e){return it.error=e,it}}function y(t,e,n,r){try{t.call(e,n,r)}catch(o){return o}}function m(t,e,n){J(function(t){var r=!1,o=y(n,e,function(n){r||(r=!0,e!==n?g(t,n):S(t,n))},function(e){r||(r=!0,j(t,e))},"Settle: "+(t._label||" unknown promise"));!r&&o&&(r=!0,j(t,o))},t)}function b(t,e){e._state===rt?S(t,e._result):e._state===ot?j(t,e._result):E(e,void 0,function(e){return g(t,e)},function(e){return j(t,e)})}function w(t,n,r){n.constructor===t.constructor&&r===l&&n.constructor.resolve===h?b(t,n):r===it?(j(t,it.error),it.error=null):void 0===r?S(t,n):e(r)?m(t,n,r):S(t,n)}function g(e,n){e===n?j(e,v()):t(n)?w(e,n,_(n)):S(e,n)}function A(t){t._onerror&&t._onerror(t._result),T(t)}function S(t,e){t._state===nt&&(t._result=e,t._state=rt,0!==t._subscribers.length&&J(T,t))}function j(t,e){t._state===nt&&(t._state=ot,t._result=e,J(A,t))}function E(t,e,n,r){var o=t._subscribers,i=o.length;t._onerror=null,o[i]=e,o[i+rt]=n,o[i+ot]=r,0===i&&t._state&&J(T,t)}function T(t){var e=t._subscribers,n=t._state;if(0!==e.length){for(var r=void 0,o=void 0,i=t._result,s=0;s<e.length;s+=3)r=e[s],o=e[s+n],r?x(n,r,o,i):o(i);t._subscribers.length=0}}function M(){this.error=null}function P(t,e){try{return t(e)}catch(n){return st.error=n,st}}function x(t,n,r,o){var i=e(r),s=void 0,u=void 0,c=void 0,a=void 0;if(i){if(s=P(r,o),s===st?(a=!0,u=s.error,s.error=null):c=!0,n===s)return void j(n,d())}else s=o,c=!0;n._state!==nt||(i&&c?g(n,s):a?j(n,u):t===rt?S(n,s):t===ot&&j(n,s))}function C(t,e){try{e(function(e){g(t,e)},function(e){j(t,e)})}catch(n){j(t,n)}}function O(){return ut++}function k(t){t[et]=ut++,t._state=void 0,t._result=void 0,t._subscribers=[]}function Y(t,e){this._instanceConstructor=t,this.promise=new t(p),this.promise[et]||k(this.promise),B(e)?(this.length=e.length,this._remaining=e.length,this._result=new Array(this.length),0===this.length?S(this.promise,this._result):(this.length=this.length||0,this._enumerate(e),0===this._remaining&&S(this.promise,this._result))):j(this.promise,q())}function q(){return new Error("Array Methods must be provided an Array")}function F(t){return new Y(this,t).promise}function D(t){var e=this;return new e(B(t)?function(n,r){for(var o=t.length,i=0;i<o;i++)e.resolve(t[i]).then(n,r)}:function(t,e){return e(new TypeError("You must pass an array to race."))})}function K(t){var e=this,n=new e(p);return j(n,t),n}function L(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function N(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function U(t){this[et]=O(),this._result=this._state=void 0,this._subscribers=[],p!==t&&("function"!=typeof t&&L(),this instanceof U?C(this,t):N())}function W(){var t=void 0;if("undefined"!=typeof global)t=global;else if("undefined"!=typeof self)t=self;else try{t=Function("return this")()}catch(e){throw new Error("polyfill failed because global object is unavailable in this environment")}var n=t.Promise;if(n){var r=null;try{r=Object.prototype.toString.call(n.resolve())}catch(e){}if("[object Promise]"===r&&!n.cast)return}t.Promise=U}var z=void 0;z=Array.isArray?Array.isArray:function(t){return"[object Array]"===Object.prototype.toString.call(t)};var B=z,G=0,H=void 0,I=void 0,J=function(t,e){$[G]=t,$[G+1]=e,G+=2,2===G&&(I?I(a):tt())},Q="undefined"!=typeof window?window:void 0,R=Q||{},V=R.MutationObserver||R.WebKitMutationObserver,X="undefined"==typeof self&&"undefined"!=typeof process&&"[object process]"==={}.toString.call(process),Z="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,$=new Array(1e3),tt=void 0;tt=X?o():V?s():Z?u():void 0===Q&&"function"==typeof require?f():c();var et=Math.random().toString(36).substring(16),nt=void 0,rt=1,ot=2,it=new M,st=new M,ut=0;return Y.prototype._enumerate=function(t){for(var e=0;this._state===nt&&e<t.length;e++)this._eachEntry(t[e],e)},Y.prototype._eachEntry=function(t,e){var n=this._instanceConstructor,r=n.resolve;if(r===h){var o=_(t);if(o===l&&t._state!==nt)this._settledAt(t._state,e,t._result);else if("function"!=typeof o)this._remaining--,this._result[e]=t;else if(n===U){var i=new n(p);w(i,t,o),this._willSettleAt(i,e)}else this._willSettleAt(new n(function(e){return e(t)}),e)}else this._willSettleAt(r(t),e)},Y.prototype._settledAt=function(t,e,n){var r=this.promise;r._state===nt&&(this._remaining--,t===ot?j(r,n):this._result[e]=n),0===this._remaining&&S(r,this._result)},Y.prototype._willSettleAt=function(t,e){var n=this;E(t,void 0,function(t){return n._settledAt(rt,e,t)},function(t){return n._settledAt(ot,e,t)})},U.all=F,U.race=D,U.resolve=h,U.reject=K,U._setScheduler=n,U._setAsap=r,U._asap=J,U.prototype={constructor:U,then:l,"catch":function(t){return this.then(null,t)}},U.polyfill=W,U.Promise=U,U.polyfill(),U});
\ No newline at end of file
This diff is collapsed.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>阿里云 JavaScript上传SDK Demo (使用jquery)</title>
<script src="./lib/jquery.min.js"></script>
<script src="./lib/aliyun-upload-sdk/aliyun-upload-sdk-1.5.2.min.js"></script>
<script src="./lib/aliyun-upload-sdk/lib/es6-promise.min.js"></script>
<script src="./lib/aliyun-upload-sdk/lib/aliyun-oss-sdk-6.13.0.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="setting">
<div class="input-control">
<label for="timeout">请求过期时间(配置项 timeout, 默认 60000):</label>
<input type="text" id="timeout" placeholder="输入过期时间, 单位毫秒">
</div>
<div class="input-control">
<label for="partSize">分片大小(配置项 partSize, 默认 1048576):</label>
<input type="text" class="form-control" id="partSize" placeholder="输入分片大小, 单位bit, 最小100k">
</div>
<div class="input-control">
<label for="parallel">上传分片数(配置项 parallel, 默认 5):</label>
<input type="text" class="form-control" id="parallel" placeholder="输入并行上传分片个数, 默认为5">
</div>
<div class="input-control">
<label for="retryCount">网络失败重试次数(配置项 retryCount, 默认 3):</label>
<input type="text" class="form-control" id="retryCount" placeholder="输入网络失败重试次数, 默认为3">
</div>
<div class="input-control">
<label for="retryDuration">网络失败重试间隔(配置项 retryDuration, 默认 2):</label>
<input type="text" class="form-control" id="retryDuration" placeholder="输入网络失败重试间隔, 默认2秒">
</div>
<div class="input-control">
<label for="region">配置项 region, 默认 cn-shanghai:</label>
<select id="region">
<option>cn-shanghai</option>
<option>eu-central-1</option>
<option>ap-southeast-1</option>
</select>
</div>
<div class="input-control">
<label for="userId">阿里云账号ID:</label>
<input type="text" value="1338241234116556" disabled class="form-control" id="userId" placeholder="输入阿里云账号ID">
集成产品后需要使用用户自己的账号ID, <a href="https://help.aliyun.com/knowledge_detail/37196.html
-"target="_blank">如何获取帐号ID</a>
</div>
</div>
<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 src="upload-auth.js"></script>
</body>
</html>
\ No newline at end of file
//兼容IE11
if (!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 binary
pt.content = binary;
pt.onload()
}
reader.readAsArrayBuffer(fileData);
}
}
var userId;
var region;
$(document).ready(function () {
if(!userId && !region){
var url = "http://test2.qiankundata.com:60081/online-edu-backend/api/aliyun/mgr/videoConfig";
$.get(url,function(data){
userId = data.datas.userId;
region = data.datas.region;
$('#userId').val(userId);
$('#region').val(region);
},'json');
}
/**
* 创建一个上传对象
* 使用 UploadAuth 上传方式
*/
function createUploader () {
var uploader = new AliyunUpload.Vod({
timeout: $('#timeout').val() || 60000,
partSize: $('#partSize').val() || 1048576,
parallel: $('#parallel').val() || 5,
retryCount: $('#retryCount').val() || 3,
retryDuration: $('#retryDuration').val() || 2,
region: region,
userId: userId,
// 添加文件成功
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 = 'http://test2.qiankundata.com:60081/online-edu-backend/api/aliyun/mgr/videoUploadPolicy?title='+ '测试视频' + '&fileName=' + uploadInfo.file.name
$.get(createUrl, function (data) {
var uploadAuth = data.datas.uploadAuth
var uploadAddress = data.datas.uploadAddress
var videoId = data.datas.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.BoYYcY
var refreshUrl = 'http://test2.qiankundata.com:60081/online-edu-backend/api/aliyun/mgr/refreshVideoUploadPolicy?VideoId=' + uploadInfo.videoId
$.get(refreshUrl, function (data) {
var uploadAuth = data.datas.uploadAuth
var uploadAddress = data.datas.uploadAddress
var videoId = data.datas.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 = 'http://test2.qiankundata.com:60081/online-edu-backend/api/aliyun/mgr/refreshVideoUploadPolicy?VideoId=' + uploadInfo.videoId
$.get(refreshUrl, function (data) {
var uploadAuth = data.datas.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)
}
})
})
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment