Browse Source

Refactor all AssetManager files in classes

pull/4219/head
Artur Arseniev 5 years ago
parent
commit
c2041c6e59
  1. 2
      src/asset_manager/index.js
  2. 16
      src/asset_manager/model/Asset.js
  3. 38
      src/asset_manager/model/Assets.js
  4. 28
      src/asset_manager/view/AssetImageView.js
  5. 18
      src/asset_manager/view/AssetView.js
  6. 46
      src/asset_manager/view/AssetsView.js
  7. 688
      src/asset_manager/view/FileUploader.js

2
src/asset_manager/index.js

@ -46,7 +46,7 @@
*/
import { debounce, isFunction } from 'underscore';
import Module from 'common/module';
import { Module } from '../common';
import defaults from './config/config';
import Asset from './model/Assets';
import Assets from './model/Assets';

16
src/asset_manager/model/Asset.js

@ -1,5 +1,5 @@
import { result } from 'underscore';
import { Model } from 'common';
import { Model } from '../../common';
/**
* @property {String} type Asset type, eg. 'image'.
@ -9,7 +9,7 @@ export default class Asset extends Model {
defaults() {
return {
type: '',
src: ''
src: '',
};
}
@ -45,11 +45,7 @@ export default class Asset extends Model {
* asset.getFilename(); // -> 'image'
* */
getFilename() {
return this.get('src')
.split('/')
.pop()
.split('?')
.shift();
return this.get('src').split('/').pop().split('?').shift();
}
/**
@ -62,14 +58,12 @@ export default class Asset extends Model {
* asset.getExtension(); // -> ''
* */
getExtension() {
return this.getFilename()
.split('.')
.pop();
return this.getFilename().split('.').pop();
}
}
Asset.prototype.idAttribute = 'src';
Asset.getDefaults = function() {
Asset.getDefaults = function () {
return result(this.prototype, 'defaults');
};

38
src/asset_manager/model/Assets.js

@ -1,23 +1,23 @@
import Backbone from 'backbone';
import { Collection } from '../../common';
import AssetImage from './AssetImage';
import AssetImageView from './../view/AssetImageView';
import TypeableCollection from 'domain_abstract/model/TypeableCollection';
import TypeableCollection from '../../domain_abstract/model/TypeableCollection';
export default Backbone.Collection.extend(TypeableCollection).extend({
types: [
{
id: 'image',
model: AssetImage,
view: AssetImageView,
isType(value) {
if (typeof value == 'string') {
return {
type: 'image',
src: value
};
}
return value;
export default class Assets extends Collection.extend(TypeableCollection) {}
Assets.prototype.types = [
{
id: 'image',
model: AssetImage,
view: AssetImageView,
isType(value) {
if (typeof value == 'string') {
return {
type: 'image',
src: value,
};
}
}
]
});
return value;
},
},
];

28
src/asset_manager/view/AssetImageView.js

@ -1,14 +1,8 @@
import { isFunction } from 'underscore';
import AssetView from './AssetView';
import html from 'utils/html';
export default AssetView.extend({
events: {
'click [data-toggle=asset-remove]': 'onRemove',
click: 'onClick',
dblclick: 'onDblClick'
},
import html from '../../utils/html';
export default class AssetImageView extends AssetView {
getPreview() {
const { pfx, ppfx, model } = this;
const src = model.get('src');
@ -16,7 +10,7 @@ export default AssetView.extend({
<div class="${pfx}preview" style="background-image: url('${src}');"></div>
<div class="${pfx}preview-bg ${ppfx}checker-bg"></div>
`;
},
}
getInfo() {
const { pfx, model } = this;
@ -30,12 +24,12 @@ export default AssetView.extend({
<div class="${pfx}name">${name}</div>
<div class="${pfx}dimensions">${dim}</div>
`;
},
}
init(o) {
const pfx = this.pfx;
this.className += ` ${pfx}asset-image`;
},
}
/**
* Triggered when the asset is clicked
@ -56,7 +50,7 @@ export default AssetView.extend({
} else {
this.updateTarget(coll.target);
}
},
}
/**
* Triggered when the asset is double clicked
@ -77,7 +71,7 @@ export default AssetView.extend({
em && em.get('Modal').close();
}
isFunction(onSelect) && onSelect(model);
},
}
/**
* Remove asset from collection
@ -87,4 +81,10 @@ export default AssetView.extend({
e.stopImmediatePropagation();
this.model.collection.remove(this.model);
}
});
}
AssetImageView.prototype.events = {
'click [data-toggle=asset-remove]': 'onRemove',
click: 'onClick',
dblclick: 'onDblClick',
};

18
src/asset_manager/view/AssetView.js

@ -1,7 +1,7 @@
import Backbone from 'backbone';
import { View } from '../../common';
import { clone } from 'underscore';
export default Backbone.View.extend({
export default class AssetView extends View {
initialize(o = {}) {
this.options = o;
this.collection = o.collection;
@ -15,13 +15,13 @@ export default Backbone.View.extend({
this.model.view = this;
const init = this.init && this.init.bind(this);
init && init(o);
},
}
__getBhv() {
const { em } = this;
const am = em && em.get('AssetManager');
return (am && am.__getBehaviour()) || {};
},
}
template() {
const pfx = this.pfx;
@ -36,7 +36,7 @@ export default Backbone.View.extend({
&Cross;
</div>
`;
},
}
/**
* Update target if exists
@ -48,15 +48,15 @@ export default Backbone.View.extend({
target.set('attributes', clone(target.get('attributes')));
target.set('src', this.model.get('src'));
}
},
}
getPreview() {
return '';
},
}
getInfo() {
return '';
},
}
render() {
const el = this.el;
@ -64,4 +64,4 @@ export default Backbone.View.extend({
el.className = this.className;
return this;
}
});
}

46
src/asset_manager/view/AssetsView.js

@ -1,11 +1,7 @@
import Backbone from 'backbone';
import { View } from '../../common';
export default Backbone.View.extend({
events: {
submit: 'handleSubmit'
},
template({ pfx, ppfx, em, ...view }) {
export default class AssetsView extends View {
template({ pfx, ppfx, em }) {
let form = '';
if (this.config.showUrlInput) {
form = `
@ -13,8 +9,7 @@ export default Backbone.View.extend({
<div class="${ppfx}field ${pfx}add-field">
<input placeholder="${em && em.t('assetManager.inputPlh')}"/>
</div>
<button class="${ppfx}btn-prim">${em &&
em.t('assetManager.addButton')}</button>
<button class="${ppfx}btn-prim">${em && em.t('assetManager.addButton')}</button>
<div style="clear:both"></div>
</form>
`;
@ -29,7 +24,7 @@ export default Backbone.View.extend({
<div style="clear:both"></div>
</div>
`;
},
}
initialize(o) {
this.options = o;
@ -42,7 +37,7 @@ export default Backbone.View.extend({
this.listenTo(coll, 'add', this.addToAsset);
this.listenTo(coll, 'remove', this.removedAsset);
this.listenTo(coll, 'deselectAll', this.deselectAll);
},
}
/**
* Add new asset to the collection via string
@ -68,7 +63,7 @@ export default Backbone.View.extend({
} else {
this.options.globalCollection.add(url, { at: 0 });
}
},
}
/**
* Returns assets element
@ -78,7 +73,7 @@ export default Backbone.View.extend({
getAssetsEl() {
//if(!this.assets) // Not able to cache as after the rerender it losses the ref
return this.el.querySelector(`.${this.pfx}assets`);
},
}
/**
* Returns input url element
@ -86,10 +81,9 @@ export default Backbone.View.extend({
* @private
*/
getAddInput() {
if (!this.inputUrl || !this.inputUrl.value)
this.inputUrl = this.el.querySelector(`.${this.pfx}add-asset input`);
if (!this.inputUrl || !this.inputUrl.value) this.inputUrl = this.el.querySelector(`.${this.pfx}add-asset input`);
return this.inputUrl;
},
}
/**
* Triggered when an asset is removed
@ -100,7 +94,7 @@ export default Backbone.View.extend({
if (!this.collection.length) {
this.toggleNoAssets();
}
},
}
/**
* Add asset to collection
@ -111,7 +105,7 @@ export default Backbone.View.extend({
this.toggleNoAssets(1);
}
this.addAsset(model);
},
}
/**
* Add new asset to collection
@ -127,7 +121,7 @@ export default Backbone.View.extend({
const rendered = new model.typeView({
model,
collection,
config
config,
}).render().el;
if (fragment) {
@ -140,7 +134,7 @@ export default Backbone.View.extend({
}
return rendered;
},
}
/**
* Checks if to show noAssets
@ -156,7 +150,7 @@ export default Backbone.View.extend({
const noAssets = this.config.noAssets;
noAssets && assetsEl.append(noAssets);
}
},
}
/**
* Deselect all assets
@ -165,7 +159,7 @@ export default Backbone.View.extend({
deselectAll() {
const pfx = this.pfx;
this.$el.find(`.${pfx}highlight`).removeClass(`${pfx}highlight`);
},
}
renderAssets() {
const fragment = document.createDocumentFragment();
@ -174,7 +168,7 @@ export default Backbone.View.extend({
this.toggleNoAssets(this.collection.length);
this.collection.each(model => this.addAsset(model, fragment));
assets.append(fragment);
},
}
render() {
const fuRendered = this.options.fu.render().el;
@ -184,4 +178,8 @@ export default Backbone.View.extend({
this.renderAssets();
return this;
}
});
}
AssetsView.prototype.events = {
submit: 'handleSubmit',
};

688
src/asset_manager/view/FileUploader.js

@ -1,381 +1,369 @@
import Backbone from 'backbone';
import fetch from 'utils/fetch';
import html from 'utils/html';
export default Backbone.View.extend(
{
template({ pfx, title, uploadId, disabled, multiUpload }) {
return html`
<form>
<div id="${pfx}title">${title}</div>
<input
type="file"
id="${uploadId}"
name="file"
accept="*/*"
${disabled ? 'disabled' : ''}
${multiUpload ? 'multiple' : ''}
/>
<div style="clear:both;"></div>
</form>
`;
},
import { View } from '../../common';
import fetch from '../../utils/fetch';
import html from '../../utils/html';
export default class FileUploaderView extends View {
template({ pfx, title, uploadId, disabled, multiUpload }) {
return html`
<form>
<div id="${pfx}title">${title}</div>
<input
type="file"
id="${uploadId}"
name="file"
accept="*/*"
${disabled ? 'disabled' : ''}
${multiUpload ? 'multiple' : ''}
/>
<div style="clear:both;"></div>
</form>
`;
}
events: {},
initialize(opts = {}) {
this.options = opts;
const c = opts.config || {};
this.module = opts.module;
this.config = c;
this.em = this.config.em;
this.pfx = c.stylePrefix || '';
this.ppfx = c.pStylePrefix || '';
this.target = this.options.globalCollection || {};
this.uploadId = this.pfx + 'uploadFile';
this.disabled =
c.disableUpload !== undefined
? c.disableUpload
: !c.upload && !c.embedAsBase64;
this.multiUpload = c.multiUpload !== undefined ? c.multiUpload : true;
this.events['change #' + this.uploadId] = 'uploadFile';
let uploadFile = c.uploadFile;
if (uploadFile) {
this.uploadFile = uploadFile.bind(this);
} else if (!c.upload && c.embedAsBase64) {
this.uploadFile = this.constructor.embedAsBase64;
}
initialize(opts = {}) {
this.options = opts;
const c = opts.config || {};
this.module = opts.module;
this.config = c;
this.em = this.config.em;
this.pfx = c.stylePrefix || '';
this.ppfx = c.pStylePrefix || '';
this.target = this.options.globalCollection || {};
this.uploadId = this.pfx + 'uploadFile';
this.disabled = c.disableUpload !== undefined ? c.disableUpload : !c.upload && !c.embedAsBase64;
this.multiUpload = c.multiUpload !== undefined ? c.multiUpload : true;
this.events = {
[`change #${this.uploadId}`]: 'uploadFile',
};
let uploadFile = c.uploadFile;
if (uploadFile) {
this.uploadFile = uploadFile.bind(this);
} else if (!c.upload && c.embedAsBase64) {
this.uploadFile = this.constructor.embedAsBase64;
}
this.delegateEvents();
},
this.delegateEvents();
}
/**
* Triggered before the upload is started
* @private
*/
onUploadStart() {
const { module } = this;
module && module.__propEv('asset:upload:start');
},
/**
* Triggered before the upload is started
* @private
*/
onUploadStart() {
const { module } = this;
module && module.__propEv('asset:upload:start');
}
/**
* Triggered after the upload is ended
* @param {Object|string} res End result
* @private
*/
onUploadEnd(res) {
const { $el, module } = this;
module && module.__propEv('asset:upload:end', res);
const input = $el.find('input');
input && input.val('');
},
/**
* Triggered after the upload is ended
* @param {Object|string} res End result
* @private
*/
onUploadEnd(res) {
const { $el, module } = this;
module && module.__propEv('asset:upload:end', res);
const input = $el.find('input');
input && input.val('');
}
/**
* Triggered on upload error
* @param {Object} err Error
* @private
*/
onUploadError(err) {
const { module } = this;
console.error(err);
this.onUploadEnd(err);
module && module.__propEv('asset:upload:error', err);
},
/**
* Triggered on upload error
* @param {Object} err Error
* @private
*/
onUploadError(err) {
const { module } = this;
console.error(err);
this.onUploadEnd(err);
module && module.__propEv('asset:upload:error', err);
}
/**
* Triggered on upload response
* @param {string} text Response text
* @private
*/
onUploadResponse(text, clb) {
const { module, config, target } = this;
let json;
try {
json = typeof text === 'string' ? JSON.parse(text) : text;
} catch (e) {
json = text;
}
/**
* Triggered on upload response
* @param {string} text Response text
* @private
*/
onUploadResponse(text, clb) {
const { module, config, target } = this;
let json;
try {
json = typeof text === 'string' ? JSON.parse(text) : text;
} catch (e) {
json = text;
}
module && module.__propEv('asset:upload:response', json);
module && module.__propEv('asset:upload:response', json);
if (config.autoAdd && target) {
target.add(json.data, { at: 0 });
}
if (config.autoAdd && target) {
target.add(json.data, { at: 0 });
}
this.onUploadEnd(text);
clb && clb(json);
},
this.onUploadEnd(text);
clb && clb(json);
}
/**
* Upload files
* @param {Object} e Event
* @return {Promise}
* @private
* */
uploadFile(e, clb) {
const files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
const { config } = this;
const { beforeUpload } = config;
const beforeUploadResponse = beforeUpload && beforeUpload(files);
if (beforeUploadResponse === false) return;
const body = new FormData();
const { params, customFetch } = config;
for (let param in params) {
body.append(param, params[param]);
}
/**
* Upload files
* @param {Object} e Event
* @return {Promise}
* @private
* */
uploadFile(e, clb) {
const files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
const { config } = this;
const { beforeUpload } = config;
const beforeUploadResponse = beforeUpload && beforeUpload(files);
if (beforeUploadResponse === false) return;
const body = new FormData();
const { params, customFetch } = config;
for (let param in params) {
body.append(param, params[param]);
}
if (this.multiUpload) {
for (let i = 0; i < files.length; i++) {
body.append(`${config.uploadName}[]`, files[i]);
}
} else if (files.length) {
body.append(config.uploadName, files[0]);
if (this.multiUpload) {
for (let i = 0; i < files.length; i++) {
body.append(`${config.uploadName}[]`, files[i]);
}
} else if (files.length) {
body.append(config.uploadName, files[0]);
}
var target = this.target;
const url = config.upload;
const headers = config.headers;
const reqHead = 'X-Requested-With';
var target = this.target;
const url = config.upload;
const headers = config.headers;
const reqHead = 'X-Requested-With';
if (typeof headers[reqHead] == 'undefined') {
headers[reqHead] = 'XMLHttpRequest';
}
if (typeof headers[reqHead] == 'undefined') {
headers[reqHead] = 'XMLHttpRequest';
}
if (url) {
this.onUploadStart();
const fetchOpts = {
method: 'post',
credentials: config.credentials || 'include',
headers,
body
if (url) {
this.onUploadStart();
const fetchOpts = {
method: 'post',
credentials: config.credentials || 'include',
headers,
body,
};
const fetchResult = customFetch
? customFetch(url, fetchOpts)
: fetch(url, fetchOpts).then(res =>
((res.status / 200) | 0) == 1 ? res.text() : res.text().then(text => Promise.reject(text))
);
return fetchResult.then(text => this.onUploadResponse(text, clb)).catch(err => this.onUploadError(err));
}
}
/**
* Make input file droppable
* @private
* */
initDrop() {
var that = this;
if (!this.uploadForm) {
this.uploadForm = this.$el.find('form').get(0);
if ('draggable' in this.uploadForm) {
var uploadFile = this.uploadFile;
this.uploadForm.ondragover = function () {
this.className = that.pfx + 'hover';
return false;
};
this.uploadForm.ondragleave = function () {
this.className = '';
return false;
};
this.uploadForm.ondrop = function (e) {
this.className = '';
e.preventDefault();
that.uploadFile(e);
return;
};
const fetchResult = customFetch
? customFetch(url, fetchOpts)
: fetch(url, fetchOpts).then(res =>
((res.status / 200) | 0) == 1
? res.text()
: res.text().then(text => Promise.reject(text))
);
return fetchResult
.then(text => this.onUploadResponse(text, clb))
.catch(err => this.onUploadError(err));
}
},
}
}
/**
* Make input file droppable
* @private
* */
initDrop() {
var that = this;
if (!this.uploadForm) {
this.uploadForm = this.$el.find('form').get(0);
if ('draggable' in this.uploadForm) {
var uploadFile = this.uploadFile;
this.uploadForm.ondragover = function() {
this.className = that.pfx + 'hover';
return false;
};
this.uploadForm.ondragleave = function() {
this.className = '';
return false;
};
this.uploadForm.ondrop = function(e) {
this.className = '';
e.preventDefault();
that.uploadFile(e);
return;
};
}
initDropzone(ev) {
let addedCls = 0;
const c = this.config;
const em = ev.model;
const edEl = ev.el;
const editor = em.get('Editor');
const container = em.get('Config').el;
const frameEl = em.get('Canvas').getBody();
const ppfx = this.ppfx;
const updatedCls = `${ppfx}dropzone-active`;
const dropzoneCls = `${ppfx}dropzone`;
const cleanEditorElCls = () => {
edEl.className = edEl.className.replace(updatedCls, '').trim();
addedCls = 0;
};
const onDragOver = () => {
if (!addedCls) {
edEl.className += ` ${updatedCls}`;
addedCls = 1;
}
},
initDropzone(ev) {
let addedCls = 0;
const c = this.config;
const em = ev.model;
const edEl = ev.el;
const editor = em.get('Editor');
const container = em.get('Config').el;
const frameEl = em.get('Canvas').getBody();
const ppfx = this.ppfx;
const updatedCls = `${ppfx}dropzone-active`;
const dropzoneCls = `${ppfx}dropzone`;
const cleanEditorElCls = () => {
edEl.className = edEl.className.replace(updatedCls, '').trim();
addedCls = 0;
};
const onDragOver = () => {
if (!addedCls) {
edEl.className += ` ${updatedCls}`;
addedCls = 1;
}
return false;
};
const onDragLeave = () => {
cleanEditorElCls();
return false;
};
const onDrop = e => {
cleanEditorElCls();
e.preventDefault();
e.stopPropagation();
this.uploadFile(e);
if (c.openAssetsOnDrop && editor) {
const target = editor.getSelected();
editor.runCommand('open-assets', {
target,
onSelect() {
editor.Modal.close();
editor.AssetManager.setTarget(null);
}
});
}
return false;
};
ev.$el.append(`<div class="${dropzoneCls}">${c.dropzoneContent}</div>`);
return false;
};
const onDragLeave = () => {
cleanEditorElCls();
if ('draggable' in edEl) {
[edEl, frameEl].forEach(item => {
item.ondragover = onDragOver;
item.ondragleave = onDragLeave;
item.ondrop = onDrop;
return false;
};
const onDrop = e => {
cleanEditorElCls();
e.preventDefault();
e.stopPropagation();
this.uploadFile(e);
if (c.openAssetsOnDrop && editor) {
const target = editor.getSelected();
editor.runCommand('open-assets', {
target,
onSelect() {
editor.Modal.close();
editor.AssetManager.setTarget(null);
},
});
}
},
render() {
const { $el, pfx, em } = this;
$el.html(
this.template({
title: em && em.t('assetManager.uploadTitle'),
uploadId: this.uploadId,
disabled: this.disabled,
multiUpload: this.multiUpload,
pfx
})
);
this.initDrop();
$el.attr('class', pfx + 'file-uploader');
return this;
return false;
};
ev.$el.append(`<div class="${dropzoneCls}">${c.dropzoneContent}</div>`);
cleanEditorElCls();
if ('draggable' in edEl) {
[edEl, frameEl].forEach(item => {
item.ondragover = onDragOver;
item.ondragleave = onDragLeave;
item.ondrop = onDrop;
});
}
},
{
embedAsBase64: function(e, clb) {
// List files dropped
const files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
const response = { data: [] };
// Unlikely, widely supported now
if (!FileReader) {
this.onUploadError(
new Error('Unsupported platform, FileReader is not defined')
);
return;
}
}
const promises = [];
const mimeTypeMatcher = /^(.+)\/(.+)$/;
for (const file of files) {
// For each file a reader (to read the base64 URL)
// and a promise (to track and merge results and errors)
const promise = new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener('load', event => {
let type;
const name = file.name;
// Try to find the MIME type of the file.
const match = mimeTypeMatcher.exec(file.type);
if (match) {
type = match[1]; // The first part in the MIME, "image" in image/png
} else {
type = file.type;
}
/*
// Show local video files, http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/
var URL = window.URL || window.webkitURL
var file = this.files[0]
var type = file.type
var videoNode = document.createElement('video');
var canPlay = videoNode.canPlayType(type) // can use also for 'audio' types
if (canPlay === '') canPlay = 'no'
var message = 'Can play type "' + type + '": ' + canPlay
var isError = canPlay === 'no'
displayMessage(message, isError)
if (isError) {
return
}
var fileURL = URL.createObjectURL(file)
videoNode.src = fileURL
*/
// If it's an image, try to find its size
if (type === 'image') {
const data = {
src: reader.result,
name,
type,
height: 0,
width: 0
};
const image = new Image();
image.addEventListener('error', error => {
reject(error);
});
image.addEventListener('load', () => {
data.height = image.height;
data.width = image.width;
resolve(data);
});
image.src = data.src;
} else if (type) {
// Not an image, but has a type
resolve({
src: reader.result,
name,
type
});
} else {
// No type found, resolve with the URL only
resolve(reader.result);
}
});
reader.addEventListener('error', error => {
reject(error);
});
reader.addEventListener('abort', error => {
reject('Aborted');
});
render() {
const { $el, pfx, em } = this;
$el.html(
this.template({
title: em && em.t('assetManager.uploadTitle'),
uploadId: this.uploadId,
disabled: this.disabled,
multiUpload: this.multiUpload,
pfx,
})
);
this.initDrop();
$el.attr('class', pfx + 'file-uploader');
return this;
}
}
reader.readAsDataURL(file);
});
FileUploaderView.embedAsBase64 = function (e, clb) {
// List files dropped
const files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
const response = { data: [] };
promises.push(promise);
// Unlikely, widely supported now
if (!FileReader) {
this.onUploadError(new Error('Unsupported platform, FileReader is not defined'));
return;
}
const promises = [];
const mimeTypeMatcher = /^(.+)\/(.+)$/;
for (const file of files) {
// For each file a reader (to read the base64 URL)
// and a promise (to track and merge results and errors)
const promise = new Promise((resolve, reject) => {
const reader = new FileReader();
reader.addEventListener('load', event => {
let type;
const name = file.name;
// Try to find the MIME type of the file.
const match = mimeTypeMatcher.exec(file.type);
if (match) {
type = match[1]; // The first part in the MIME, "image" in image/png
} else {
type = file.type;
}
/*
// Show local video files, http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/
var URL = window.URL || window.webkitURL
var file = this.files[0]
var type = file.type
var videoNode = document.createElement('video');
var canPlay = videoNode.canPlayType(type) // can use also for 'audio' types
if (canPlay === '') canPlay = 'no'
var message = 'Can play type "' + type + '": ' + canPlay
var isError = canPlay === 'no'
displayMessage(message, isError)
if (isError) {
return
}
Promise.all(promises).then(
data => {
response.data = data;
this.onUploadResponse(response, clb);
},
error => {
this.onUploadError(error);
var fileURL = URL.createObjectURL(file)
videoNode.src = fileURL
*/
// If it's an image, try to find its size
if (type === 'image') {
const data = {
src: reader.result,
name,
type,
height: 0,
width: 0,
};
const image = new Image();
image.addEventListener('error', error => {
reject(error);
});
image.addEventListener('load', () => {
data.height = image.height;
data.width = image.width;
resolve(data);
});
image.src = data.src;
} else if (type) {
// Not an image, but has a type
resolve({
src: reader.result,
name,
type,
});
} else {
// No type found, resolve with the URL only
resolve(reader.result);
}
);
}
});
reader.addEventListener('error', error => {
reject(error);
});
reader.addEventListener('abort', error => {
reject('Aborted');
});
reader.readAsDataURL(file);
});
promises.push(promise);
}
);
Promise.all(promises).then(
data => {
response.data = data;
this.onUploadResponse(response, clb);
},
error => {
this.onUploadError(error);
}
);
};

Loading…
Cancel
Save