///
$(document).ready(function(){ UploadForm(); Sys.WebForms.PageRequestManager.getInstance().add_endRequest(WireUp); })
// Builds a single file upload form
function UploadForm() {
'use strict';
// Initialize the jQuery File Upload widget:
WireUp();
// Open download dialogs via iframes,
// to prevent aborting current uploads:
$(document).on('click', '[id^="fileupload"] .files a:not([target^=_blank])', function (e) {
e.preventDefault();
$('')
.prop('src', this.href)
.appendTo('body');
});
}
var canShowCard = false;
const acceptExpressions = [ { 'image': '/(\.|\/)(gif|jpe?g|png)$/i' }, { 'video': '/(\.|\/)(mov|mpe?g|mp4|m4a)$/i' }];
// individual wire up
function WireUp(){
canShowCard = typeof(Card) == 'function';
var uploaderPrefix = 'fileupload_';
var _path = '/handlers/DragNDrop/UploadHandler.ashx'; //$(location).attr('pathname') + '/UploadFile';
$('div[id^=' + uploaderPrefix + ']').each(function () {
// mark as wired up
if (MarkAsWiredUp(this)) return;
// get the extra form data
this.payload = readyPayload(this);
// old timey work around
var _limit = undefined;
_limit = LookUpFromPayload(_limit, 'limit', this.payload);
if (_limit == 'true') _limit = 1;
else _limit = undefined;
// get the filetype expression
var acceptFileTypesKey = '';
acceptFileTypesKey = LookUpFromPayload(acceptFileTypesKey, 'mime-type', this.payload);
//var acceptFileTypes = acceptExpressions[acceptFileTypesKey];
if (acceptFileTypesKey != '') {
// update the input
$(this).find('input[type="file"]').attr('accept', acceptFileTypesKey.split('/')[0] + '/*');
}
var maxFileSize = 10000000; // default from blueimp dev
maxFileSize = LookUpFromPayload(maxFileSize, '', this.payload);
//height=500|input=width=500
$(this).fileupload({
url: _path, // instead post back to the page and use the handler code
formData: this.payload,
limitMultiFileUploads: _limit,
//acceptFileTypes: acceptFileTypes,
maxFileSize: maxFileSize,
imageOrientation: true,
previewOrientation: true,
autoUpload: true,
done: DoneWithSingleFile,
error: HandleError,
add: AddImageToUpload
//card: typeof(Card) == 'function' ? new Card ($(this)) : null
});
});
}
function MarkAsWiredUp(input) {
var isWiredUp = $(input).attr('data_wiredup');
if (isWiredUp == 'true') return true;
else $(input).attr('data_wiredup', 'true');
return false;
}
function HandleError(e, data) {
NotifyOfFailure(e.target);
}
// method to handle adder callback
function AddImageToUpload(e, data) {
var input = $(e.target);
// optionally pop the progress
if($(input).find('input[name="bubble"]').length > 0) $('div[id$="ctl00_upProg"]').fadeIn();
// handle alternate progress indicator
if (canShowCard) new Card(input).PresentProgress();
checkAndHandoff(input, data, this.payload);
}
function checkAndHandoff(input, data, payload) {
var isVideo = '';
isVideo = LookUpFromPayload(isVideo, 'mime-type', payload).includes('video');
PermissionsCheck(isVideo, data.files[0]).then(function(check) {
if (check.canUpload) {
if (isVideo) {
var videoProcessingMessage = 'Video has been uploaded and is being processed';
videoProcessingMessage = LookUpFromPayload(videoProcessingMessage, 'videoprocessingmessage', payload);
//GetScreenshot(check.video).then(function(imageLoad) {
if (canShowCard) new Card(input).PresentProgress('', videoProcessingMessage);
data.submit();
//});
}
else UploadImage(data.files[0]).then(function(response) {
if (response.isReady) {
if (response.imageBlob) data.files[0] = response.imageBlob;
data.submit();
}
else NotifyOfFailure(input, isVideo, ' due to a failure to correct EXIF data');
});
}
else NotifyOfFailure(input, isVideo, check.message);
});
}
function GetScreenshot(video) {
return new Promise(function(resolve) {
var imageLoad = '';
if (video && !!window.HTMLCanvasElement) { // canvas supported
var canvas = document.createElement('canvas');
$(canvas).width(video.videoWidth);
$(canvas).height(video.videoHeight);
// grab from middle by dividing
canvas.ontimeupdate = function() {
canvas.getContext('2d').drawImage(video, 0, 0, video.videoWidth, video.videoHeight);
var base64Image = canvas.toDataURL();
if (base64Image && base64Image.length > 0) imageLoad = base64Image;
resolve(imageLoad);
};
video.currentTime = video.duration / 2;
}
else resolve(imageLoad);
});
}
function readyPayload(input) {
var payload = scanForOptions(input);
$.each([{ name: 'multiple', value: 'false' }, { name: 'rename', value: '' }, { name: 'height', value: '0' }, { name: 'width', value: '0' }, { name: 'mime-type', value: '' },
{ name: 'extension', value: '' }, { name: 'maxsize', value: '' }, { name: 'maxspace', value: '' }, { name: 'codec', value: '' }, { name: 'prefix', value: '' },
{ name: 'useroot', value: '' }, { name: 'domain', value: '0' }, { name: 'OverrideInitialNumbering', value: 'false' }, { name: 'useyoutube', value: 'false' }, { name: 'usevimeo', value: 'false' },
{ name: 'title', value: '' }, { name: 'description', value: '' }],
function () {
var addToList = true;
var that = this;
$.each(payload, function() { addToList = addToList && this.name != that.name });
if (addToList) payload[payload.length] = { name: that.name, value: that.value };
}); // NOTE: this is named for conformity
return payload;
}
function scanForOptions(input) {
var payload = [];
$(input).find('input').each(function(f) {
var name = $(this).attr('name');
var valu = $(this).val();
if (name == 'maxup') {
name = 'multiple';
valu = (valu === '0') ? 'true' : 'false';
}
else if (name == 'userootpath') name = 'useroot';
else if (valu === undefined) valu = '';
payload[payload.length] = { name: name, value: valu };
});
return payload;
}
function PermissionsCheck(isVideo, videoFile) {
return new Promise(function(resolve) {
var canUpload = !isVideo;
var resolution = { canUpload: canUpload, video: null, message: ' due to insufficient permissions' };
if (isVideo)
{
// look up maxvideos
var maxDuration = 0;
maxDuration = LookUpFromPayload(maxDuration, 'MaxVideoDuration');
/*window.URL = window.URL || window.webkitURL;
var video = document.createElement('video');
video.preload = 'metadata';
video.onloadmetadata = function() {
window.URL.revokeObjectURL(video.src);
}
video.src = URL.createObjectURL(data.files[0]);
console.log(video.duration);*/
//alert(videoFile.name);
if (videoFile.name.toLowerCase().endsWith('.mov')) {
resolution.canUpload = true;
//resolution.video = video;
resolve(resolution);
}
else {
var reader = new FileReader();
reader.onload = function(e) {
var video = document.createElement('video');
video.src = e.target.result;
video.type = 'video/mp4';
//if (videoFile.name.endsWith('.mov')) video.type = 'video/quicktime';
var timer = setInterval(function() {
if (video.readyState===4) {
clearInterval(timer);
canUpload = video.duration < maxDuration;
if (!canUpload) resolution.message = ' because the video exceeds the maximum duration of ' + maxDuration + ' seconds.';
resolution.canUpload = canUpload;
resolution.video = video;
resolve(resolution);
}
else if (video.error) {
clearInterval(time);
resolution.canUpload = false;
resolution.message = ' because of a problem with the video file.';
resolve(resolution);
}
}, 500);
}
reader.readAsDataURL(videoFile);
}
}
else resolve(resolution);
});
}
function UploadImage(file) {
return new Promise(function (resolve) {
var resolution = { isReady: false, imageBlob: null };
loadImage(file, function (img, meta)
{
if (meta.imageHead && meta.exif) {
var rotateBuffer = loadImage.writeExifData(meta.imageHead, meta, 'Orientation', 1);
img.toBlob(function (blob) {
loadImage.replaceHead(blob, meta.imageHead, function (imageBlob) {
resolution.isReady = true;
resolution.imageBlob = imageBlob;
resolve(resolution);
});
}, 'image/jpeg');
}
else {
resolution.isReady = true;
resolve(resolution);
}
}, { meta: true, orientation: true, canvas: true });
});
}
function NotifyOfFailure(input, isVideo, debugMessage) {
// determine message then determine delivery
var failsafeMessage = "Failed to upload";
var message = LookUpFromPayload(message, 'FailedMessage');
if (isVideo) message = LookUpFromPayload(message, 'FailedVideoMessage');
message = message && message.length > 0 ? message : failsafeMessage;
if (message.length > 0) message = message + debugMessage;
if (canShowCard) new Card(input).PresentProgress('', message);
else alert(message);
}
// handles completed uploads
function DoneWithSingleFile(e, data) {
if (data.textStatus == "success") {
//if (this.card) this.card.ParseUploadData(data);
if (canShowCard) new Card(e.target).ParseUploadData(data);
else __doPostBack($(this).attr('id'),'');
}
else NotifyOfFailure(e.target, false, '; could not process on the server');
}
function LookUpFromPayload(source, key, payload) {
var value = '';
if (payload) $.each(payload, function() { if (this.name == key) value = this.value; });
else $('#' + key).each(function(e) { value = $(this).val(); });
return value && (!(typeof(value) === 'string') || value.length > 0) ? value : source;
}