ionic 本地視訊上傳與預覽圖擷取上傳
阿新 • • 發佈:2018-11-08
input file 觸發
<input type="file" accept="video/avi,video/mp4,video/flv,video/3gp,video/swf" onchange="angular.element(this).scope().onFileChange(this.files)" style="display: none;">
上傳視訊按鈕
<a type="button" class="button button-small button-outline button-stable" ng-click="addVideo()">上傳本地視訊 </a>
視訊預覽
<video onloadeddata="angular.element(this).scope().onLoadedData()" id="previewVideo" ng-show="videoFile||videoFileName" controls="controls" style="width: 100%">
<source src="{{videoFile}}"/>
</video>
按鈕點選事件
$scope.addVideo=function(){ var els = document.querySelectorAll('input[type=file]'); els[0].click(); }
file change 事件
$scope.onFileChange=function(files){ $scope.videoFileName = files[0].name; //視訊預覽 fileReader.readAsDataUrl(files[0],$scope) .then(function (result) { document.getElementById("previewVideo").src=result; }); $scope.$apply(); //這裡使用了 ng-file-upload 檔案上傳外掛 Upload.upload({ //服務端接收 url: ApiUrl.url+"user/video", file: files[0] }).progress(function (evt) { //進度條 var progressPercentage = parseInt(100.0 * evt.loaded / evt.total); $timeout(function () { $ionicLoading.show({ template: "正在上傳:" + Math.floor(progressPercentage) + "%" }); if (progressPercentage > 99) { $ionicLoading.hide(); } }) }).success(function (data, status, headers, config) { //上傳成功 var resultUrl = data.replace(/(^\s*)|(\s*$)/g, "");//後臺返回出現*符號 ,清除 $scope.videoPath = resultUrl; console.log($scope.videoPath); $ionicLoading.hide(); $cordovaToast.showShortTop("上傳成功"); }).error(function (data, status, headers, config){ $ionicLoading.hide(); $cordovaToast.showShortTop("上傳失敗"); }); }
視訊預覽時觸發 onloadeddata 事件,這裡上傳預覽圖
//base64轉blob(後臺只接收file)
$scope.convertBase64UrlToBlob=function(dataurl){
var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1], bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr],{ type: 'image/png' }); }
//canvas 生成視訊預覽圖並上傳
$scope.onLoadedData=function(){
var scale = 0.8;
var video = document.getElementById("previewVideo");
$rootScope.videoPreviewPlay = video;
var canvas = document.createElement("canvas");
canvas.width = video.videoWidth * scale;
canvas.height = video.videoHeight * scale;
canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
var img_preview = canvas.toDataURL("image/png");
var file = $scope.convertBase64UrlToBlob(img_preview);
var fd = new FormData();
fd.append('file', file , "image.png"); // 移動端好像要加第三個引數,否則預覽圖無法上傳成功
$http({
method : 'POST',
url : ApiUrl.url+"user/image",
data : fd, //僅僅存放的是檔案流資料
headers : {
'Content-Type' : undefined //angularjs設定檔案上傳的content-type修改方式
},
transformRequest : angular.identity,
}).success(function(response) {
var resultUrl = response.replace(/(^\s*)|(\s*$)/g, "");
$scope.imgPreview = ApiUrl.imageUrl+resultUrl;
}).error(function(err){
});
}