code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function StripTagBody(tags, next) {
if (typeof next !== "function") {
next = function () {};
}
var isRemoveAllTag = !Array.isArray(tags);
function isRemoveTag(tag) {
if (isRemoveAllTag) return true;
return _.indexOf(tags, tag) !== -1;
}
var removeList = [];
var posStart = false;
return {
onIgnoreTag: function (tag, html, options) {
if (isRemoveTag(tag)) {
if (options.isClosing) {
var ret = "[/removed]";
var end = options.position + ret.length;
removeList.push([
posStart !== false ? posStart : options.position,
end,
]);
posStart = false;
return ret;
} else {
if (!posStart) {
posStart = options.position;
}
return "[removed]";
}
} else {
return next(tag, html, options);
}
},
remove: function (html) {
var rethtml = "";
var lastPos = 0;
_.forEach(removeList, function (pos) {
rethtml += html.slice(lastPos, pos[0]);
lastPos = pos[1];
});
rethtml += html.slice(lastPos);
return rethtml;
},
};
}
|
remove tag body
specify a `tags` list, if the tag is not in the `tags` list then process by the specify function (optional)
@param {array} tags
@param {function} next
|
StripTagBody
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function isRemoveTag(tag) {
if (isRemoveAllTag) return true;
return _.indexOf(tags, tag) !== -1;
}
|
remove tag body
specify a `tags` list, if the tag is not in the `tags` list then process by the specify function (optional)
@param {array} tags
@param {function} next
|
isRemoveTag
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function stripCommentTag(html) {
var retHtml = "";
var lastPos = 0;
while (lastPos < html.length) {
var i = html.indexOf("<!--", lastPos);
if (i === -1) {
retHtml += html.slice(lastPos);
break;
}
retHtml += html.slice(lastPos, i);
var j = html.indexOf("-->", i);
if (j === -1) {
break;
}
lastPos = j + 3;
}
return retHtml;
}
|
remove html comments
@param {String} html
@return {String}
|
stripCommentTag
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function stripBlankChar(html) {
var chars = html.split("");
chars = chars.filter(function (char) {
var c = char.charCodeAt(0);
if (c === 127) return false;
if (c <= 31) {
if (c === 10 || c === 13) return true;
return false;
}
return true;
});
return chars.join("");
}
|
remove invisible characters
@param {String} html
@return {String}
|
stripBlankChar
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function filterXSS(html, options) {
var xss = new FilterXSS(options);
return xss.process(html);
}
|
filter xss function
@param {String} html
@param {Object} options { whiteList, onTag, onTagAttr, onIgnoreTag, onIgnoreTagAttr, safeAttrValue, escapeHtml }
@return {String}
|
filterXSS
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function isWorkerEnv() {
return (
typeof self !== "undefined" &&
typeof DedicatedWorkerGlobalScope !== "undefined" &&
self instanceof DedicatedWorkerGlobalScope
);
}
|
filter xss function
@param {String} html
@param {Object} options { whiteList, onTag, onTagAttr, onIgnoreTag, onIgnoreTagAttr, safeAttrValue, escapeHtml }
@return {String}
|
isWorkerEnv
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function getTagName(html) {
var i = _.spaceIndex(html);
var tagName;
if (i === -1) {
tagName = html.slice(1, -1);
} else {
tagName = html.slice(1, i + 1);
}
tagName = _.trim(tagName).toLowerCase();
if (tagName.slice(0, 1) === "/") tagName = tagName.slice(1);
if (tagName.slice(-1) === "/") tagName = tagName.slice(0, -1);
return tagName;
}
|
get tag name
@param {String} html e.g. '<a hef="#">'
@return {String}
|
getTagName
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function parseTag(html, onTag, escapeHtml) {
"use strict";
var rethtml = "";
var lastPos = 0;
var tagStart = false;
var quoteStart = false;
var currentPos = 0;
var len = html.length;
var currentTagName = "";
var currentHtml = "";
chariterator: for (currentPos = 0; currentPos < len; currentPos++) {
var c = html.charAt(currentPos);
if (tagStart === false) {
if (c === "<") {
tagStart = currentPos;
continue;
}
} else {
if (quoteStart === false) {
if (c === "<") {
rethtml += escapeHtml(html.slice(lastPos, currentPos));
tagStart = currentPos;
lastPos = currentPos;
continue;
}
if (c === ">" || currentPos === len - 1) {
rethtml += escapeHtml(html.slice(lastPos, tagStart));
currentHtml = html.slice(tagStart, currentPos + 1);
currentTagName = getTagName(currentHtml);
rethtml += onTag(
tagStart,
rethtml.length,
currentTagName,
currentHtml,
isClosing(currentHtml)
);
lastPos = currentPos + 1;
tagStart = false;
continue;
}
if (c === '"' || c === "'") {
var i = 1;
var ic = html.charAt(currentPos - i);
while (ic.trim() === "" || ic === "=") {
if (ic === "=") {
quoteStart = c;
continue chariterator;
}
ic = html.charAt(currentPos - ++i);
}
}
} else {
if (c === quoteStart) {
quoteStart = false;
continue;
}
}
}
}
if (lastPos < len) {
rethtml += escapeHtml(html.substr(lastPos));
}
return rethtml;
}
|
parse input html and returns processed html
@param {String} html
@param {Function} onTag e.g. function (sourcePosition, position, tag, html, isClosing)
@param {Function} escapeHtml
@return {String}
|
parseTag
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function addAttr(name, value) {
name = _.trim(name);
name = name.replace(REGEXP_ILLEGAL_ATTR_NAME, "").toLowerCase();
if (name.length < 1) return;
var ret = onAttr(name, value || "");
if (ret) retAttrs.push(ret);
}
|
parse input attributes and returns processed attributes
@param {String} html e.g. `href="#" target="_blank"`
@param {Function} onAttr e.g. `function (name, value)`
@return {String}
|
addAttr
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function findNextEqual(str, i) {
for (; i < str.length; i++) {
var c = str[i];
if (c === " ") continue;
if (c === "=") return i;
return -1;
}
}
|
parse input attributes and returns processed attributes
@param {String} html e.g. `href="#" target="_blank"`
@param {Function} onAttr e.g. `function (name, value)`
@return {String}
|
findNextEqual
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function findNextQuotationMark(str, i) {
for (; i < str.length; i++) {
var c = str[i];
if (c === " ") continue;
if (c === "'" || c === '"') return i;
return -1;
}
}
|
parse input attributes and returns processed attributes
@param {String} html e.g. `href="#" target="_blank"`
@param {Function} onAttr e.g. `function (name, value)`
@return {String}
|
findNextQuotationMark
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function findBeforeEqual(str, i) {
for (; i > 0; i--) {
var c = str[i];
if (c === " ") continue;
if (c === "=") return i;
return -1;
}
}
|
parse input attributes and returns processed attributes
@param {String} html e.g. `href="#" target="_blank"`
@param {Function} onAttr e.g. `function (name, value)`
@return {String}
|
findBeforeEqual
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function isQuoteWrapString(text) {
if (
(text[0] === '"' && text[text.length - 1] === '"') ||
(text[0] === "'" && text[text.length - 1] === "'")
) {
return true;
} else {
return false;
}
}
|
parse input attributes and returns processed attributes
@param {String} html e.g. `href="#" target="_blank"`
@param {Function} onAttr e.g. `function (name, value)`
@return {String}
|
isQuoteWrapString
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function stripQuoteWrap(text) {
if (isQuoteWrapString(text)) {
return text.substr(1, text.length - 2);
} else {
return text;
}
}
|
parse input attributes and returns processed attributes
@param {String} html e.g. `href="#" target="_blank"`
@param {Function} onAttr e.g. `function (name, value)`
@return {String}
|
stripQuoteWrap
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function isNull(obj) {
return obj === undefined || obj === null;
}
|
returns `true` if the input value is `undefined` or `null`
@param {Object} obj
@return {Boolean}
|
isNull
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function getAttrs(html) {
var i = _.spaceIndex(html);
if (i === -1) {
return {
html: "",
closing: html[html.length - 2] === "/",
};
}
html = _.trim(html.slice(i + 1, -1));
var isClosing = html[html.length - 1] === "/";
if (isClosing) html = _.trim(html.slice(0, -1));
return {
html: html,
closing: isClosing,
};
}
|
get attributes for a tag
@param {String} html
@return {Object}
- {String} html
- {Boolean} closing
|
getAttrs
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function shallowCopyObject(obj) {
var ret = {};
for (var i in obj) {
ret[i] = obj[i];
}
return ret;
}
|
shallow copy
@param {Object} obj
@return {Object}
|
shallowCopyObject
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function keysToLowerCase(obj) {
var ret = {};
for (var i in obj) {
if (Array.isArray(obj[i])) {
ret[i.toLowerCase()] = obj[i].map(function (item) {
return item.toLowerCase();
});
} else {
ret[i.toLowerCase()] = obj[i];
}
}
return ret;
}
|
shallow copy
@param {Object} obj
@return {Object}
|
keysToLowerCase
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
function FilterXSS(options) {
options = shallowCopyObject(options || {});
if (options.stripIgnoreTag) {
if (options.onIgnoreTag) {
console.error(
'Notes: cannot use these two options "stripIgnoreTag" and "onIgnoreTag" at the same time'
);
}
options.onIgnoreTag = DEFAULT.onIgnoreTagStripAll;
}
if (options.whiteList || options.allowList) {
options.whiteList = keysToLowerCase(options.whiteList || options.allowList);
} else {
options.whiteList = DEFAULT.whiteList;
}
options.onTag = options.onTag || DEFAULT.onTag;
options.onTagAttr = options.onTagAttr || DEFAULT.onTagAttr;
options.onIgnoreTag = options.onIgnoreTag || DEFAULT.onIgnoreTag;
options.onIgnoreTagAttr = options.onIgnoreTagAttr || DEFAULT.onIgnoreTagAttr;
options.safeAttrValue = options.safeAttrValue || DEFAULT.safeAttrValue;
options.escapeHtml = options.escapeHtml || DEFAULT.escapeHtml;
this.options = options;
if (options.css === false) {
this.cssFilter = false;
} else {
options.css = options.css || {};
this.cssFilter = new FilterCSS(options.css);
}
}
|
FilterXSS class
@param {Object} options
whiteList (or allowList), onTag, onTagAttr, onIgnoreTag,
onIgnoreTagAttr, safeAttrValue, escapeHtml
stripIgnoreTagBody, allowCommentTag, stripBlankChar
css{whiteList, onAttr, onIgnoreAttr} `css=false` means don't use `cssfilter`
|
FilterXSS
|
javascript
|
TavernAI/TavernAI
|
public/scripts/xss.js
|
https://github.com/TavernAI/TavernAI/blob/master/public/scripts/xss.js
|
MIT
|
_extend = function (dst){
var args = arguments, i = 1, _ext = function (val, key){ dst[key] = val; };
for( ; i < args.length; i++ ){
_each(args[i], _ext);
}
return dst;
}
|
Merge the contents of two or more objects together into the first object
|
_extend
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
|
MIT
|
function Image(file){
if( file instanceof Image ){
var img = new Image(file.file);
api.extend(img.matrix, file.matrix);
return img;
}
else if( !(this instanceof Image) ){
return new Image(file);
}
this.file = file;
this.size = file.size || 100;
this.matrix = {
sx: 0,
sy: 0,
sw: 0,
sh: 0,
dx: 0,
dy: 0,
dw: 0,
dh: 0,
resize: 0, // min, max OR preview
deg: 0,
quality: 1, // jpeg quality
filter: 0
};
}
|
Remove drag'n'drop
@param {HTMLElement} el
@param {Function} onHover
@param {Function} onDrop
|
Image
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
|
MIT
|
fn = function (){
var
x = over.x|0
, y = over.y|0
, w = over.w || img.width
, h = over.h || img.height
, rel = over.rel
;
// center | right | left
x = (rel == 1 || rel == 4 || rel == 7) ? (dw - w + x)/2 : (rel == 2 || rel == 5 || rel == 8 ? dw - (w + x) : x);
// center | bottom | top
y = (rel == 3 || rel == 4 || rel == 5) ? (dh - h + y)/2 : (rel >= 6 ? dh - (h + y) : y);
api.event.off(img, 'error load abort', fn);
try {
ctx.globalAlpha = over.opacity || 1;
ctx.drawImage(img, x, y, w, h);
}
catch (er){}
queue.next();
}
|
Remove drag'n'drop
@param {HTMLElement} el
@param {Function} onHover
@param {Function} onDrop
|
fn
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
|
MIT
|
function _transform(err, img){
// img -- info object
var
images = {}
, queue = api.queue(function (err){
fn(err, images);
})
;
if( !err ){
api.each(transform, function (params, name){
if( !queue.isFail() ){
var ImgTrans = new Image(img.nodeType ? img : file), isFn = typeof params == 'function';
if( isFn ){
params(img, ImgTrans);
}
else if( params.width ){
ImgTrans[params.preview ? 'preview' : 'resize'](params.width, params.height, params.strategy);
}
else {
if( params.maxWidth && (img.width > params.maxWidth || img.height > params.maxHeight) ){
ImgTrans.resize(params.maxWidth, params.maxHeight, 'max');
}
}
if( params.crop ){
var crop = params.crop;
ImgTrans.crop(crop.x|0, crop.y|0, crop.w || crop.width, crop.h || crop.height);
}
if( params.rotate === undef && autoOrientation ){
params.rotate = 'auto';
}
ImgTrans.set({ type: ImgTrans.matrix.type || params.type || file.type || 'image/png' });
if( !isFn ){
ImgTrans.set({
deg: params.rotate
, overlay: params.overlay
, filter: params.filter
, quality: params.quality || 1
});
}
queue.inc();
ImgTrans.toData(function (err, image){
if( err ){
queue.fail();
}
else {
images[name] = image;
queue.next();
}
});
}
});
}
else {
queue.fail();
}
}
|
Remove drag'n'drop
@param {HTMLElement} el
@param {Function} onHover
@param {Function} onDrop
|
_transform
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
|
MIT
|
_complete = function (err){
_this._active = !err;
clearTimeout(_failId);
clearTimeout(_successId);
// api.event.off(video, 'loadedmetadata', _complete);
callback && callback(err, _this);
}
|
Start camera streaming
@param {Function} callback
|
_complete
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
|
MIT
|
doneFn = function (err){
if( err ){
callback(err);
}
else {
// Get camera
var cam = Camera.get(el);
if( options.start ){
cam.start(callback);
}
else {
callback(null, cam);
}
}
}
|
Publish camera element into container
@static
@param {HTMLElement} el
@param {Object} options
@param {Function} [callback]
|
doneFn
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
|
MIT
|
function _px(val){
return val >= 0 ? val + 'px' : val;
}
|
Add "px" postfix, if value is a number
@private
@param {*} val
@return {String}
|
_px
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
|
MIT
|
function _detectVideoSignal(video){
var canvas = document.createElement('canvas'), ctx, res = false;
try {
ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, 1, 1);
res = ctx.getImageData(0, 0, 1, 1).data[4] != 255;
}
catch( e ){}
return res;
}
|
@private
@param {HTMLVideoElement} video
@return {Boolean}
|
_detectVideoSignal
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
|
MIT
|
function _wrap(fn) {
var id = fn.wid = api.uid();
api.Flash._fn[id] = fn;
return 'FileAPI.Flash._fn.' + id;
}
|
FileAPI fallback to Flash
@flash-developer "Vladimir Demidov" <[email protected]>
|
_wrap
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
|
MIT
|
function _unwrap(fn) {
try {
api.Flash._fn[fn.wid] = null;
delete api.Flash._fn[fn.wid];
} catch (e) {
}
}
|
FileAPI fallback to Flash
@flash-developer "Vladimir Demidov" <[email protected]>
|
_unwrap
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/FileAPI.js
|
MIT
|
function sendHttp(config) {
config.method = config.method || 'POST';
config.headers = config.headers || {};
var deferred = config._deferred = config._deferred || $q.defer();
var promise = deferred.promise;
function notifyProgress(e) {
if (deferred.notify) {
deferred.notify(e);
}
if (promise.progressFunc) {
$timeout(function () {
promise.progressFunc(e);
});
}
}
function getNotifyEvent(n) {
if (config._start != null && resumeSupported) {
return {
loaded: n.loaded + config._start,
total: (config._file && config._file.size) || n.total,
type: n.type, config: config,
lengthComputable: true, target: n.target
};
} else {
return n;
}
}
if (!config.disableProgress) {
config.headers.__setXHR_ = function () {
return function (xhr) {
if (!xhr || !xhr.upload || !xhr.upload.addEventListener) return;
config.__XHR = xhr;
if (config.xhrFn) config.xhrFn(xhr);
xhr.upload.addEventListener('progress', function (e) {
e.config = config;
notifyProgress(getNotifyEvent(e));
}, false);
//fix for firefox not firing upload progress end, also IE8-9
xhr.upload.addEventListener('load', function (e) {
if (e.lengthComputable) {
e.config = config;
notifyProgress(getNotifyEvent(e));
}
}, false);
};
};
}
function uploadWithAngular() {
$http(config).then(function (r) {
if (resumeSupported && config._chunkSize && !config._finished && config._file) {
var fileSize = config._file && config._file.size || 0;
notifyProgress({
loaded: Math.min(config._end, fileSize),
total: fileSize,
config: config,
type: 'progress'
}
);
upload.upload(config, true);
} else {
if (config._finished) delete config._finished;
deferred.resolve(r);
}
}, function (e) {
deferred.reject(e);
}, function (n) {
deferred.notify(n);
}
);
}
if (!resumeSupported) {
uploadWithAngular();
} else if (config._chunkSize && config._end && !config._finished) {
config._start = config._end;
config._end += config._chunkSize;
uploadWithAngular();
} else if (config.resumeSizeUrl) {
$http.get(config.resumeSizeUrl).then(function (resp) {
if (config.resumeSizeResponseReader) {
config._start = config.resumeSizeResponseReader(resp.data);
} else {
config._start = parseInt((resp.data.size == null ? resp.data : resp.data.size).toString());
}
if (config._chunkSize) {
config._end = config._start + config._chunkSize;
}
uploadWithAngular();
}, function (e) {
throw e;
});
} else if (config.resumeSize) {
config.resumeSize().then(function (size) {
config._start = size;
if (config._chunkSize) {
config._end = config._start + config._chunkSize;
}
uploadWithAngular();
}, function (e) {
throw e;
});
} else {
if (config._chunkSize) {
config._start = 0;
config._end = config._start + config._chunkSize;
}
uploadWithAngular();
}
promise.success = function (fn) {
promise.then(function (response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function (fn) {
promise.then(null, function (response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.progress = function (fn) {
promise.progressFunc = fn;
promise.then(null, null, function (n) {
fn(n);
});
return promise;
};
promise.abort = promise.pause = function () {
if (config.__XHR) {
$timeout(function () {
config.__XHR.abort();
});
}
return promise;
};
promise.xhr = function (fn) {
config.xhrFn = (function (origXhrFn) {
return function () {
if (origXhrFn) origXhrFn.apply(promise, arguments);
fn.apply(promise, arguments);
};
})(config.xhrFn);
return promise;
};
upload.promisesCount++;
if (promise['finally'] && promise['finally'] instanceof Function) {
promise['finally'](function () {
upload.promisesCount--;
});
}
return promise;
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
sendHttp
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function notifyProgress(e) {
if (deferred.notify) {
deferred.notify(e);
}
if (promise.progressFunc) {
$timeout(function () {
promise.progressFunc(e);
});
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
notifyProgress
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function getNotifyEvent(n) {
if (config._start != null && resumeSupported) {
return {
loaded: n.loaded + config._start,
total: (config._file && config._file.size) || n.total,
type: n.type, config: config,
lengthComputable: true, target: n.target
};
} else {
return n;
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
getNotifyEvent
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function uploadWithAngular() {
$http(config).then(function (r) {
if (resumeSupported && config._chunkSize && !config._finished && config._file) {
var fileSize = config._file && config._file.size || 0;
notifyProgress({
loaded: Math.min(config._end, fileSize),
total: fileSize,
config: config,
type: 'progress'
}
);
upload.upload(config, true);
} else {
if (config._finished) delete config._finished;
deferred.resolve(r);
}
}, function (e) {
deferred.reject(e);
}, function (n) {
deferred.notify(n);
}
);
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
uploadWithAngular
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function copy(obj) {
var clone = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = obj[key];
}
}
return clone;
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
copy
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function toResumeFile(file, formData) {
if (file._ngfBlob) return file;
config._file = config._file || file;
if (config._start != null && resumeSupported) {
if (config._end && config._end >= file.size) {
config._finished = true;
config._end = file.size;
}
var slice = file.slice(config._start, config._end || file.size);
slice.name = file.name;
slice.ngfName = file.ngfName;
if (config._chunkSize) {
formData.append('_chunkSize', config._chunkSize);
formData.append('_currentChunkSize', config._end - config._start);
formData.append('_chunkNumber', Math.floor(config._start / config._chunkSize));
formData.append('_totalSize', config._file.size);
}
return slice;
}
return file;
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
toResumeFile
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function addFieldToFormData(formData, val, key) {
if (val !== undefined) {
if (angular.isDate(val)) {
val = val.toISOString();
}
if (angular.isString(val)) {
formData.append(key, val);
} else if (upload.isFile(val)) {
var file = toResumeFile(val, formData);
var split = key.split(',');
if (split[1]) {
file.ngfName = split[1].replace(/^\s+|\s+$/g, '');
key = split[0];
}
config._fileKey = config._fileKey || key;
formData.append(key, file, file.ngfName || file.name);
} else {
if (angular.isObject(val)) {
if (val.$$ngfCircularDetection) throw 'ngFileUpload: Circular reference in config.data. Make sure specified data for Upload.upload() has no circular reference: ' + key;
val.$$ngfCircularDetection = true;
try {
for (var k in val) {
if (val.hasOwnProperty(k) && k !== '$$ngfCircularDetection') {
var objectKey = config.objectKey == null ? '[i]' : config.objectKey;
if (val.length && parseInt(k) > -1) {
objectKey = config.arrayKey == null ? objectKey : config.arrayKey;
}
addFieldToFormData(formData, val[k], key + objectKey.replace(/[ik]/g, k));
}
}
} finally {
delete val.$$ngfCircularDetection;
}
} else {
formData.append(key, val);
}
}
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
addFieldToFormData
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function digestConfig() {
config._chunkSize = upload.translateScalars(config.resumeChunkSize);
config._chunkSize = config._chunkSize ? parseInt(config._chunkSize.toString()) : null;
config.headers = config.headers || {};
config.headers['Content-Type'] = undefined;
config.transformRequest = config.transformRequest ?
(angular.isArray(config.transformRequest) ?
config.transformRequest : [config.transformRequest]) : [];
config.transformRequest.push(function (data) {
var formData = new window.FormData(), key;
data = data || config.fields || {};
if (config.file) {
data.file = config.file;
}
for (key in data) {
if (data.hasOwnProperty(key)) {
var val = data[key];
if (config.formDataAppender) {
config.formDataAppender(formData, key, val);
} else {
addFieldToFormData(formData, val, key);
}
}
}
return formData;
});
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
digestConfig
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function applyExifRotations(files, attr, scope) {
var promises = [upload.emptyPromise()];
angular.forEach(files, function (f, i) {
if (f.type.indexOf('image/jpeg') === 0 && upload.attrGetter('ngfFixOrientation', attr, scope, {$file: f})) {
promises.push(upload.happyPromise(upload.applyExifRotation(f), f).then(function (fixedFile) {
files.splice(i, 1, fixedFile);
}));
}
});
return $q.all(promises);
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
applyExifRotations
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function resizeFile(files, attr, scope, ngModel) {
var resizeVal = upload.attrGetter('ngfResize', attr, scope);
if (!resizeVal || !upload.isResizeSupported() || !files.length) return upload.emptyPromise();
if (resizeVal instanceof Function) {
var defer = $q.defer();
return resizeVal(files).then(function (p) {
resizeWithParams(p, files, attr, scope, ngModel).then(function (r) {
defer.resolve(r);
}, function (e) {
defer.reject(e);
});
}, function (e) {
defer.reject(e);
});
} else {
return resizeWithParams(resizeVal, files, attr, scope, ngModel);
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
resizeFile
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function resizeWithParams(params, files, attr, scope, ngModel) {
var promises = [upload.emptyPromise()];
function handleFile(f, i) {
if (f.type.indexOf('image') === 0) {
if (params.pattern && !upload.validatePattern(f, params.pattern)) return;
params.resizeIf = function (width, height) {
return upload.attrGetter('ngfResizeIf', attr, scope,
{$width: width, $height: height, $file: f});
};
var promise = upload.resize(f, params);
promises.push(promise);
promise.then(function (resizedFile) {
files.splice(i, 1, resizedFile);
}, function (e) {
f.$error = 'resize';
(f.$errorMessages = (f.$errorMessages || {})).resize = true;
f.$errorParam = (e ? (e.message ? e.message : e) + ': ' : '') + (f && f.name);
ngModel.$ngfValidations.push({name: 'resize', valid: false});
upload.applyModelValidation(ngModel, files);
});
}
}
for (var i = 0; i < files.length; i++) {
handleFile(files[i], i);
}
return $q.all(promises);
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
resizeWithParams
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function handleFile(f, i) {
if (f.type.indexOf('image') === 0) {
if (params.pattern && !upload.validatePattern(f, params.pattern)) return;
params.resizeIf = function (width, height) {
return upload.attrGetter('ngfResizeIf', attr, scope,
{$width: width, $height: height, $file: f});
};
var promise = upload.resize(f, params);
promises.push(promise);
promise.then(function (resizedFile) {
files.splice(i, 1, resizedFile);
}, function (e) {
f.$error = 'resize';
(f.$errorMessages = (f.$errorMessages || {})).resize = true;
f.$errorParam = (e ? (e.message ? e.message : e) + ': ' : '') + (f && f.name);
ngModel.$ngfValidations.push({name: 'resize', valid: false});
upload.applyModelValidation(ngModel, files);
});
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
handleFile
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function update(files, invalidFiles, newFiles, dupFiles, isSingleModel) {
attr.$$ngfPrevValidFiles = files;
attr.$$ngfPrevInvalidFiles = invalidFiles;
var file = files && files.length ? files[0] : null;
var invalidFile = invalidFiles && invalidFiles.length ? invalidFiles[0] : null;
if (ngModel) {
upload.applyModelValidation(ngModel, files);
ngModel.$setViewValue(isSingleModel ? file : files);
}
if (fileChange) {
$parse(fileChange)(scope, {
$files: files,
$file: file,
$newFiles: newFiles,
$duplicateFiles: dupFiles,
$invalidFiles: invalidFiles,
$invalidFile: invalidFile,
$event: evt
});
}
var invalidModel = upload.attrGetter('ngfModelInvalid', attr);
if (invalidModel) {
$timeout(function () {
$parse(invalidModel).assign(scope, isSingleModel ? invalidFile : invalidFiles);
});
}
$timeout(function () {
// scope apply changes
});
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
update
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function removeDuplicates() {
function equals(f1, f2) {
return f1.name === f2.name && (f1.$ngfOrigSize || f1.size) === (f2.$ngfOrigSize || f2.size) &&
f1.type === f2.type;
}
function isInPrevFiles(f) {
var j;
for (j = 0; j < prevValidFiles.length; j++) {
if (equals(f, prevValidFiles[j])) {
return true;
}
}
for (j = 0; j < prevInvalidFiles.length; j++) {
if (equals(f, prevInvalidFiles[j])) {
return true;
}
}
return false;
}
if (files) {
allNewFiles = [];
dupFiles = [];
for (var i = 0; i < files.length; i++) {
if (isInPrevFiles(files[i])) {
dupFiles.push(files[i]);
} else {
allNewFiles.push(files[i]);
}
}
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
removeDuplicates
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function equals(f1, f2) {
return f1.name === f2.name && (f1.$ngfOrigSize || f1.size) === (f2.$ngfOrigSize || f2.size) &&
f1.type === f2.type;
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
equals
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function isInPrevFiles(f) {
var j;
for (j = 0; j < prevValidFiles.length; j++) {
if (equals(f, prevValidFiles[j])) {
return true;
}
}
for (j = 0; j < prevInvalidFiles.length; j++) {
if (equals(f, prevInvalidFiles[j])) {
return true;
}
}
return false;
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
isInPrevFiles
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function toArray(v) {
return angular.isArray(v) ? v : [v];
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
toArray
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function resizeAndUpdate() {
function updateModel() {
$timeout(function () {
update(keep ? prevValidFiles.concat(valids) : valids,
keep ? prevInvalidFiles.concat(invalids) : invalids,
files, dupFiles, isSingleModel);
}, options && options.debounce ? options.debounce.change || options.debounce : 0);
}
var resizingFiles = validateAfterResize ? allNewFiles : valids;
resizeFile(resizingFiles, attr, scope, ngModel).then(function () {
if (validateAfterResize) {
upload.validate(allNewFiles, keep ? prevValidFiles.length : 0, ngModel, attr, scope)
.then(function (validationResult) {
valids = validationResult.validsFiles;
invalids = validationResult.invalidsFiles;
updateModel();
});
} else {
updateModel();
}
}, function () {
for (var i = 0; i < resizingFiles.length; i++) {
var f = resizingFiles[i];
if (f.$error === 'resize') {
var index = valids.indexOf(f);
if (index > -1) {
valids.splice(index, 1);
invalids.push(f);
}
updateModel();
}
}
});
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
resizeAndUpdate
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function updateModel() {
$timeout(function () {
update(keep ? prevValidFiles.concat(valids) : valids,
keep ? prevInvalidFiles.concat(invalids) : invalids,
files, dupFiles, isSingleModel);
}, options && options.debounce ? options.debounce.change || options.debounce : 0);
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
updateModel
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function isDelayedClickSupported(ua) {
// fix for android native browser < 4.4 and safari windows
var m = ua.match(/Android[^\d]*(\d+)\.(\d+)/);
if (m && m.length > 2) {
var v = Upload.defaults.androidFixMinorVersion || 4;
return parseInt(m[1]) < 4 || (parseInt(m[1]) === v && parseInt(m[2]) < v);
}
// safari on windows
return ua.indexOf('Chrome') === -1 && /.*Windows.*Safari.*/.test(ua);
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
isDelayedClickSupported
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function linkFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile, upload) {
/** @namespace attr.ngfSelect */
/** @namespace attr.ngfChange */
/** @namespace attr.ngModel */
/** @namespace attr.ngfModelOptions */
/** @namespace attr.ngfMultiple */
/** @namespace attr.ngfCapture */
/** @namespace attr.ngfValidate */
/** @namespace attr.ngfKeep */
var attrGetter = function (name, scope) {
return upload.attrGetter(name, attr, scope);
};
function isInputTypeFile() {
return elem[0].tagName.toLowerCase() === 'input' && attr.type && attr.type.toLowerCase() === 'file';
}
function fileChangeAttr() {
return attrGetter('ngfChange') || attrGetter('ngfSelect');
}
function changeFn(evt) {
if (upload.shouldUpdateOn('change', attr, scope)) {
var fileList = evt.__files_ || (evt.target && evt.target.files), files = [];
/* Handle duplicate call in IE11 */
if (!fileList) return;
for (var i = 0; i < fileList.length; i++) {
files.push(fileList[i]);
}
upload.updateModel(ngModel, attr, scope, fileChangeAttr(),
files.length ? files : null, evt);
}
}
upload.registerModelChangeValidator(ngModel, attr, scope);
var unwatches = [];
if (attrGetter('ngfMultiple')) {
unwatches.push(scope.$watch(attrGetter('ngfMultiple'), function () {
fileElem.attr('multiple', attrGetter('ngfMultiple', scope));
}));
}
if (attrGetter('ngfCapture')) {
unwatches.push(scope.$watch(attrGetter('ngfCapture'), function () {
fileElem.attr('capture', attrGetter('ngfCapture', scope));
}));
}
if (attrGetter('ngfAccept')) {
unwatches.push(scope.$watch(attrGetter('ngfAccept'), function () {
fileElem.attr('accept', attrGetter('ngfAccept', scope));
}));
}
unwatches.push(attr.$observe('accept', function () {
fileElem.attr('accept', attrGetter('accept'));
}));
function bindAttrToFileInput(fileElem, label) {
function updateId(val) {
fileElem.attr('id', 'ngf-' + val);
label.attr('id', 'ngf-label-' + val);
}
for (var i = 0; i < elem[0].attributes.length; i++) {
var attribute = elem[0].attributes[i];
if (attribute.name !== 'type' && attribute.name !== 'class' && attribute.name !== 'style') {
if (attribute.name === 'id') {
updateId(attribute.value);
unwatches.push(attr.$observe('id', updateId));
} else {
fileElem.attr(attribute.name, (!attribute.value && (attribute.name === 'required' ||
attribute.name === 'multiple')) ? attribute.name : attribute.value);
}
}
}
}
function createFileInput() {
if (isInputTypeFile()) {
return elem;
}
var fileElem = angular.element('<input type="file">');
var label = angular.element('<label>upload</label>');
label.css('visibility', 'hidden').css('position', 'absolute').css('overflow', 'hidden')
.css('width', '0px').css('height', '0px').css('border', 'none')
.css('margin', '0px').css('padding', '0px').attr('tabindex', '-1');
bindAttrToFileInput(fileElem, label);
generatedElems.push({el: elem, ref: label});
document.body.appendChild(label.append(fileElem)[0]);
return fileElem;
}
function clickHandler(evt) {
if (elem.attr('disabled')) return false;
if (attrGetter('ngfSelectDisabled', scope)) return;
var r = detectSwipe(evt);
// prevent the click if it is a swipe
if (r != null) return r;
resetModel(evt);
// fix for md when the element is removed from the DOM and added back #460
try {
if (!isInputTypeFile() && !document.body.contains(fileElem[0])) {
generatedElems.push({el: elem, ref: fileElem.parent()});
document.body.appendChild(fileElem.parent()[0]);
fileElem.bind('change', changeFn);
}
} catch (e) {/*ignore*/
}
if (isDelayedClickSupported(navigator.userAgent)) {
setTimeout(function () {
fileElem[0].click();
}, 0);
} else {
fileElem[0].click();
}
return false;
}
var initialTouchStartY = 0;
var initialTouchStartX = 0;
function detectSwipe(evt) {
var touches = evt.changedTouches || (evt.originalEvent && evt.originalEvent.changedTouches);
if (touches) {
if (evt.type === 'touchstart') {
initialTouchStartX = touches[0].clientX;
initialTouchStartY = touches[0].clientY;
return true; // don't block event default
} else {
// prevent scroll from triggering event
if (evt.type === 'touchend') {
var currentX = touches[0].clientX;
var currentY = touches[0].clientY;
if ((Math.abs(currentX - initialTouchStartX) > 20) ||
(Math.abs(currentY - initialTouchStartY) > 20)) {
evt.stopPropagation();
evt.preventDefault();
return false;
}
}
return true;
}
}
}
var fileElem = elem;
function resetModel(evt) {
if (upload.shouldUpdateOn('click', attr, scope) && fileElem.val()) {
fileElem.val(null);
upload.updateModel(ngModel, attr, scope, fileChangeAttr(), null, evt, true);
}
}
if (!isInputTypeFile()) {
fileElem = createFileInput();
}
fileElem.bind('change', changeFn);
if (!isInputTypeFile()) {
elem.bind('click touchstart touchend', clickHandler);
} else {
elem.bind('click', resetModel);
}
function ie10SameFileSelectFix(evt) {
if (fileElem && !fileElem.attr('__ngf_ie10_Fix_')) {
if (!fileElem[0].parentNode) {
fileElem = null;
return;
}
evt.preventDefault();
evt.stopPropagation();
fileElem.unbind('click');
var clone = fileElem.clone();
fileElem.replaceWith(clone);
fileElem = clone;
fileElem.attr('__ngf_ie10_Fix_', 'true');
fileElem.bind('change', changeFn);
fileElem.bind('click', ie10SameFileSelectFix);
fileElem[0].click();
return false;
} else {
fileElem.removeAttr('__ngf_ie10_Fix_');
}
}
if (navigator.appVersion.indexOf('MSIE 10') !== -1) {
fileElem.bind('click', ie10SameFileSelectFix);
}
if (ngModel) ngModel.$formatters.push(function (val) {
if (val == null || val.length === 0) {
if (fileElem.val()) {
fileElem.val(null);
}
}
return val;
});
scope.$on('$destroy', function () {
if (!isInputTypeFile()) fileElem.parent().remove();
angular.forEach(unwatches, function (unwatch) {
unwatch();
});
});
$timeout(function () {
for (var i = 0; i < generatedElems.length; i++) {
var g = generatedElems[i];
if (!document.body.contains(g.el[0])) {
generatedElems.splice(i, 1);
g.ref.remove();
}
}
});
if (window.FileAPI && window.FileAPI.ngfFixIE) {
window.FileAPI.ngfFixIE(elem, fileElem, changeFn);
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
linkFileSelect
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
calculateAspectRatioFit = function (srcWidth, srcHeight, maxWidth, maxHeight, centerCrop) {
var ratio = centerCrop ? Math.max(maxWidth / srcWidth, maxHeight / srcHeight) :
Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return {
width: srcWidth * ratio, height: srcHeight * ratio,
marginX: srcWidth * ratio - maxWidth, marginY: srcHeight * ratio - maxHeight
};
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
calculateAspectRatioFit
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
resize = function (imagen, width, height, quality, type, ratio, centerCrop, resizeIf) {
var deferred = $q.defer();
var canvasElement = document.createElement('canvas');
var imageElement = document.createElement('img');
imageElement.setAttribute('style', 'visibility:hidden;position:fixed;z-index:-100000');
document.body.appendChild(imageElement);
imageElement.onload = function () {
var imgWidth = imageElement.width, imgHeight = imageElement.height;
imageElement.parentNode.removeChild(imageElement);
if (resizeIf != null && resizeIf(imgWidth, imgHeight) === false) {
deferred.reject('resizeIf');
return;
}
try {
if (ratio) {
var ratioFloat = upload.ratioToFloat(ratio);
var imgRatio = imgWidth / imgHeight;
if (imgRatio < ratioFloat) {
width = imgWidth;
height = width / ratioFloat;
} else {
height = imgHeight;
width = height * ratioFloat;
}
}
if (!width) {
width = imgWidth;
}
if (!height) {
height = imgHeight;
}
var dimensions = calculateAspectRatioFit(imgWidth, imgHeight, width, height, centerCrop);
canvasElement.width = Math.min(dimensions.width, width);
canvasElement.height = Math.min(dimensions.height, height);
var context = canvasElement.getContext('2d');
context.drawImage(imageElement,
Math.min(0, -dimensions.marginX / 2), Math.min(0, -dimensions.marginY / 2),
dimensions.width, dimensions.height);
deferred.resolve(canvasElement.toDataURL(type || 'image/WebP', quality || 0.934));
} catch (e) {
deferred.reject(e);
}
};
imageElement.onerror = function () {
imageElement.parentNode.removeChild(imageElement);
deferred.reject();
};
imageElement.src = imagen;
return deferred.promise;
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
resize
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function linkDrop(scope, elem, attr, ngModel, $parse, $timeout, $window, upload, $http, $q) {
var available = dropAvailable();
var attrGetter = function (name, scope, params) {
return upload.attrGetter(name, attr, scope, params);
};
if (attrGetter('dropAvailable')) {
$timeout(function () {
if (scope[attrGetter('dropAvailable')]) {
scope[attrGetter('dropAvailable')].value = available;
} else {
scope[attrGetter('dropAvailable')] = available;
}
});
}
if (!available) {
if (attrGetter('ngfHideOnDropNotAvailable', scope) === true) {
elem.css('display', 'none');
}
return;
}
function isDisabled() {
return elem.attr('disabled') || attrGetter('ngfDropDisabled', scope);
}
if (attrGetter('ngfSelect') == null) {
upload.registerModelChangeValidator(ngModel, attr, scope);
}
var leaveTimeout = null;
var stopPropagation = $parse(attrGetter('ngfStopPropagation'));
var dragOverDelay = 1;
var actualDragOverClass;
elem[0].addEventListener('dragover', function (evt) {
if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
evt.preventDefault();
if (stopPropagation(scope)) evt.stopPropagation();
// handling dragover events from the Chrome download bar
if (navigator.userAgent.indexOf('Chrome') > -1) {
var b = evt.dataTransfer.effectAllowed;
evt.dataTransfer.dropEffect = ('move' === b || 'linkMove' === b) ? 'move' : 'copy';
}
$timeout.cancel(leaveTimeout);
if (!actualDragOverClass) {
actualDragOverClass = 'C';
calculateDragOverClass(scope, attr, evt, function (clazz) {
actualDragOverClass = clazz;
elem.addClass(actualDragOverClass);
attrGetter('ngfDrag', scope, {$isDragging: true, $class: actualDragOverClass, $event: evt});
});
}
}, false);
elem[0].addEventListener('dragenter', function (evt) {
if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
evt.preventDefault();
if (stopPropagation(scope)) evt.stopPropagation();
}, false);
elem[0].addEventListener('dragleave', function (evt) {
if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
evt.preventDefault();
if (stopPropagation(scope)) evt.stopPropagation();
leaveTimeout = $timeout(function () {
if (actualDragOverClass) elem.removeClass(actualDragOverClass);
actualDragOverClass = null;
attrGetter('ngfDrag', scope, {$isDragging: false, $event: evt});
}, dragOverDelay || 100);
}, false);
elem[0].addEventListener('drop', function (evt) {
if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
evt.preventDefault();
if (stopPropagation(scope)) evt.stopPropagation();
if (actualDragOverClass) elem.removeClass(actualDragOverClass);
actualDragOverClass = null;
extractFilesAndUpdateModel(evt.dataTransfer, evt, 'dropUrl');
}, false);
elem[0].addEventListener('paste', function (evt) {
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1 &&
attrGetter('ngfEnableFirefoxPaste', scope)) {
evt.preventDefault();
}
if (isDisabled() || !upload.shouldUpdateOn('paste', attr, scope)) return;
extractFilesAndUpdateModel(evt.clipboardData || evt.originalEvent.clipboardData, evt, 'pasteUrl');
}, false);
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1 &&
attrGetter('ngfEnableFirefoxPaste', scope)) {
elem.attr('contenteditable', true);
elem.on('keypress', function (e) {
if (!e.metaKey && !e.ctrlKey) {
e.preventDefault();
}
});
}
function extractFilesAndUpdateModel(source, evt, updateOnType) {
if (!source) return;
// html needs to be calculated on the same process otherwise the data will be wiped
// after promise resolve or setTimeout.
var html;
try {
html = source && source.getData && source.getData('text/html');
} catch (e) {/* Fix IE11 that throw error calling getData */
}
extractFiles(source.items, source.files, attrGetter('ngfAllowDir', scope) !== false,
attrGetter('multiple') || attrGetter('ngfMultiple', scope)).then(function (files) {
if (files.length) {
updateModel(files, evt);
} else {
extractFilesFromHtml(updateOnType, html).then(function (files) {
updateModel(files, evt);
});
}
});
}
function updateModel(files, evt) {
upload.updateModel(ngModel, attr, scope, attrGetter('ngfChange') || attrGetter('ngfDrop'), files, evt);
}
function extractFilesFromHtml(updateOn, html) {
if (!upload.shouldUpdateOn(updateOn, attr, scope) || typeof html !== 'string') return upload.rejectPromise([]);
var urls = [];
html.replace(/<(img src|img [^>]* src) *=\"([^\"]*)\"/gi, function (m, n, src) {
urls.push(src);
});
var promises = [], files = [];
if (urls.length) {
angular.forEach(urls, function (url) {
promises.push(upload.urlToBlob(url).then(function (blob) {
files.push(blob);
}));
});
var defer = $q.defer();
$q.all(promises).then(function () {
defer.resolve(files);
}, function (e) {
defer.reject(e);
});
return defer.promise;
}
return upload.emptyPromise();
}
function calculateDragOverClass(scope, attr, evt, callback) {
var obj = attrGetter('ngfDragOverClass', scope, {$event: evt}), dClass = 'dragover';
if (angular.isString(obj)) {
dClass = obj;
} else if (obj) {
if (obj.delay) dragOverDelay = obj.delay;
if (obj.accept || obj.reject) {
var items = evt.dataTransfer.items;
if (items == null || !items.length) {
dClass = obj.accept;
} else {
var pattern = obj.pattern || attrGetter('ngfPattern', scope, {$event: evt});
var len = items.length;
while (len--) {
if (!upload.validatePattern(items[len], pattern)) {
dClass = obj.reject;
break;
} else {
dClass = obj.accept;
}
}
}
}
}
callback(dClass);
}
function extractFiles(items, fileList, allowDir, multiple) {
var maxFiles = upload.getValidationAttr(attr, scope, 'maxFiles');
if (maxFiles == null) {
maxFiles = Number.MAX_VALUE;
}
var maxTotalSize = upload.getValidationAttr(attr, scope, 'maxTotalSize');
if (maxTotalSize == null) {
maxTotalSize = Number.MAX_VALUE;
}
var includeDir = attrGetter('ngfIncludeDir', scope);
var files = [], totalSize = 0;
function traverseFileTree(entry, path) {
var defer = $q.defer();
if (entry != null) {
if (entry.isDirectory) {
var promises = [upload.emptyPromise()];
if (includeDir) {
var file = {type: 'directory'};
file.name = file.path = (path || '') + entry.name;
files.push(file);
}
var dirReader = entry.createReader();
var entries = [];
var readEntries = function () {
dirReader.readEntries(function (results) {
try {
if (!results.length) {
angular.forEach(entries.slice(0), function (e) {
if (files.length <= maxFiles && totalSize <= maxTotalSize) {
promises.push(traverseFileTree(e, (path ? path : '') + entry.name + '/'));
}
});
$q.all(promises).then(function () {
defer.resolve();
}, function (e) {
defer.reject(e);
});
} else {
entries = entries.concat(Array.prototype.slice.call(results || [], 0));
readEntries();
}
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
};
readEntries();
} else {
entry.file(function (file) {
try {
file.path = (path ? path : '') + file.name;
if (includeDir) {
file = upload.rename(file, file.path);
}
files.push(file);
totalSize += file.size;
defer.resolve();
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
}
}
return defer.promise;
}
var promises = [upload.emptyPromise()];
if (items && items.length > 0 && $window.location.protocol !== 'file:') {
for (var i = 0; i < items.length; i++) {
if (items[i].webkitGetAsEntry && items[i].webkitGetAsEntry() && items[i].webkitGetAsEntry().isDirectory) {
var entry = items[i].webkitGetAsEntry();
if (entry.isDirectory && !allowDir) {
continue;
}
if (entry != null) {
promises.push(traverseFileTree(entry));
}
} else {
var f = items[i].getAsFile();
if (f != null) {
files.push(f);
totalSize += f.size;
}
}
if (files.length > maxFiles || totalSize > maxTotalSize ||
(!multiple && files.length > 0)) break;
}
} else {
if (fileList != null) {
for (var j = 0; j < fileList.length; j++) {
var file = fileList.item(j);
if (file.type || file.size > 0) {
files.push(file);
totalSize += file.size;
}
if (files.length > maxFiles || totalSize > maxTotalSize ||
(!multiple && files.length > 0)) break;
}
}
}
var defer = $q.defer();
$q.all(promises).then(function () {
if (!multiple && !includeDir && files.length) {
var i = 0;
while (files[i] && files[i].type === 'directory') i++;
defer.resolve([files[i]]);
} else {
defer.resolve(files);
}
}, function (e) {
defer.reject(e);
});
return defer.promise;
}
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
linkDrop
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
attrGetter = function (name, scope, params) {
return upload.attrGetter(name, attr, scope, params);
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
attrGetter
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function isDisabled() {
return elem.attr('disabled') || attrGetter('ngfDropDisabled', scope);
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
isDisabled
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function extractFilesAndUpdateModel(source, evt, updateOnType) {
if (!source) return;
// html needs to be calculated on the same process otherwise the data will be wiped
// after promise resolve or setTimeout.
var html;
try {
html = source && source.getData && source.getData('text/html');
} catch (e) {/* Fix IE11 that throw error calling getData */
}
extractFiles(source.items, source.files, attrGetter('ngfAllowDir', scope) !== false,
attrGetter('multiple') || attrGetter('ngfMultiple', scope)).then(function (files) {
if (files.length) {
updateModel(files, evt);
} else {
extractFilesFromHtml(updateOnType, html).then(function (files) {
updateModel(files, evt);
});
}
});
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
extractFilesAndUpdateModel
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function updateModel(files, evt) {
upload.updateModel(ngModel, attr, scope, attrGetter('ngfChange') || attrGetter('ngfDrop'), files, evt);
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
updateModel
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function extractFilesFromHtml(updateOn, html) {
if (!upload.shouldUpdateOn(updateOn, attr, scope) || typeof html !== 'string') return upload.rejectPromise([]);
var urls = [];
html.replace(/<(img src|img [^>]* src) *=\"([^\"]*)\"/gi, function (m, n, src) {
urls.push(src);
});
var promises = [], files = [];
if (urls.length) {
angular.forEach(urls, function (url) {
promises.push(upload.urlToBlob(url).then(function (blob) {
files.push(blob);
}));
});
var defer = $q.defer();
$q.all(promises).then(function () {
defer.resolve(files);
}, function (e) {
defer.reject(e);
});
return defer.promise;
}
return upload.emptyPromise();
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
extractFilesFromHtml
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function calculateDragOverClass(scope, attr, evt, callback) {
var obj = attrGetter('ngfDragOverClass', scope, {$event: evt}), dClass = 'dragover';
if (angular.isString(obj)) {
dClass = obj;
} else if (obj) {
if (obj.delay) dragOverDelay = obj.delay;
if (obj.accept || obj.reject) {
var items = evt.dataTransfer.items;
if (items == null || !items.length) {
dClass = obj.accept;
} else {
var pattern = obj.pattern || attrGetter('ngfPattern', scope, {$event: evt});
var len = items.length;
while (len--) {
if (!upload.validatePattern(items[len], pattern)) {
dClass = obj.reject;
break;
} else {
dClass = obj.accept;
}
}
}
}
}
callback(dClass);
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
calculateDragOverClass
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function extractFiles(items, fileList, allowDir, multiple) {
var maxFiles = upload.getValidationAttr(attr, scope, 'maxFiles');
if (maxFiles == null) {
maxFiles = Number.MAX_VALUE;
}
var maxTotalSize = upload.getValidationAttr(attr, scope, 'maxTotalSize');
if (maxTotalSize == null) {
maxTotalSize = Number.MAX_VALUE;
}
var includeDir = attrGetter('ngfIncludeDir', scope);
var files = [], totalSize = 0;
function traverseFileTree(entry, path) {
var defer = $q.defer();
if (entry != null) {
if (entry.isDirectory) {
var promises = [upload.emptyPromise()];
if (includeDir) {
var file = {type: 'directory'};
file.name = file.path = (path || '') + entry.name;
files.push(file);
}
var dirReader = entry.createReader();
var entries = [];
var readEntries = function () {
dirReader.readEntries(function (results) {
try {
if (!results.length) {
angular.forEach(entries.slice(0), function (e) {
if (files.length <= maxFiles && totalSize <= maxTotalSize) {
promises.push(traverseFileTree(e, (path ? path : '') + entry.name + '/'));
}
});
$q.all(promises).then(function () {
defer.resolve();
}, function (e) {
defer.reject(e);
});
} else {
entries = entries.concat(Array.prototype.slice.call(results || [], 0));
readEntries();
}
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
};
readEntries();
} else {
entry.file(function (file) {
try {
file.path = (path ? path : '') + file.name;
if (includeDir) {
file = upload.rename(file, file.path);
}
files.push(file);
totalSize += file.size;
defer.resolve();
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
}
}
return defer.promise;
}
var promises = [upload.emptyPromise()];
if (items && items.length > 0 && $window.location.protocol !== 'file:') {
for (var i = 0; i < items.length; i++) {
if (items[i].webkitGetAsEntry && items[i].webkitGetAsEntry() && items[i].webkitGetAsEntry().isDirectory) {
var entry = items[i].webkitGetAsEntry();
if (entry.isDirectory && !allowDir) {
continue;
}
if (entry != null) {
promises.push(traverseFileTree(entry));
}
} else {
var f = items[i].getAsFile();
if (f != null) {
files.push(f);
totalSize += f.size;
}
}
if (files.length > maxFiles || totalSize > maxTotalSize ||
(!multiple && files.length > 0)) break;
}
} else {
if (fileList != null) {
for (var j = 0; j < fileList.length; j++) {
var file = fileList.item(j);
if (file.type || file.size > 0) {
files.push(file);
totalSize += file.size;
}
if (files.length > maxFiles || totalSize > maxTotalSize ||
(!multiple && files.length > 0)) break;
}
}
}
var defer = $q.defer();
$q.all(promises).then(function () {
if (!multiple && !includeDir && files.length) {
var i = 0;
while (files[i] && files[i].type === 'directory') i++;
defer.resolve([files[i]]);
} else {
defer.resolve(files);
}
}, function (e) {
defer.reject(e);
});
return defer.promise;
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
extractFiles
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function traverseFileTree(entry, path) {
var defer = $q.defer();
if (entry != null) {
if (entry.isDirectory) {
var promises = [upload.emptyPromise()];
if (includeDir) {
var file = {type: 'directory'};
file.name = file.path = (path || '') + entry.name;
files.push(file);
}
var dirReader = entry.createReader();
var entries = [];
var readEntries = function () {
dirReader.readEntries(function (results) {
try {
if (!results.length) {
angular.forEach(entries.slice(0), function (e) {
if (files.length <= maxFiles && totalSize <= maxTotalSize) {
promises.push(traverseFileTree(e, (path ? path : '') + entry.name + '/'));
}
});
$q.all(promises).then(function () {
defer.resolve();
}, function (e) {
defer.reject(e);
});
} else {
entries = entries.concat(Array.prototype.slice.call(results || [], 0));
readEntries();
}
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
};
readEntries();
} else {
entry.file(function (file) {
try {
file.path = (path ? path : '') + file.name;
if (includeDir) {
file = upload.rename(file, file.path);
}
files.push(file);
totalSize += file.size;
defer.resolve();
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
}
}
return defer.promise;
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
traverseFileTree
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
readEntries = function () {
dirReader.readEntries(function (results) {
try {
if (!results.length) {
angular.forEach(entries.slice(0), function (e) {
if (files.length <= maxFiles && totalSize <= maxTotalSize) {
promises.push(traverseFileTree(e, (path ? path : '') + entry.name + '/'));
}
});
$q.all(promises).then(function () {
defer.resolve();
}, function (e) {
defer.reject(e);
});
} else {
entries = entries.concat(Array.prototype.slice.call(results || [], 0));
readEntries();
}
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
readEntries
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function dropAvailable() {
var div = document.createElement('div');
return ('draggable' in div) && ('ondrop' in div) && !/Edge\/12./i.test(navigator.userAgent);
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
dropAvailable
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function applyTransform(ctx, orientation, width, height) {
switch (orientation) {
case 2:
return ctx.transform(-1, 0, 0, 1, width, 0);
case 3:
return ctx.transform(-1, 0, 0, -1, width, height);
case 4:
return ctx.transform(1, 0, 0, -1, 0, height);
case 5:
return ctx.transform(0, 1, 1, 0, 0, 0);
case 6:
return ctx.transform(0, 1, -1, 0, height, 0);
case 7:
return ctx.transform(0, -1, -1, 0, height, width);
case 8:
return ctx.transform(0, -1, 1, 0, 0, width);
}
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
applyTransform
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
arrayBufferToBase64
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload-all.js
|
MIT
|
function sendHttp(config) {
config.method = config.method || 'POST';
config.headers = config.headers || {};
var deferred = config._deferred = config._deferred || $q.defer();
var promise = deferred.promise;
function notifyProgress(e) {
if (deferred.notify) {
deferred.notify(e);
}
if (promise.progressFunc) {
$timeout(function () {
promise.progressFunc(e);
});
}
}
function getNotifyEvent(n) {
if (config._start != null && resumeSupported) {
return {
loaded: n.loaded + config._start,
total: (config._file && config._file.size) || n.total,
type: n.type, config: config,
lengthComputable: true, target: n.target
};
} else {
return n;
}
}
if (!config.disableProgress) {
config.headers.__setXHR_ = function () {
return function (xhr) {
if (!xhr || !xhr.upload || !xhr.upload.addEventListener) return;
config.__XHR = xhr;
if (config.xhrFn) config.xhrFn(xhr);
xhr.upload.addEventListener('progress', function (e) {
e.config = config;
notifyProgress(getNotifyEvent(e));
}, false);
//fix for firefox not firing upload progress end, also IE8-9
xhr.upload.addEventListener('load', function (e) {
if (e.lengthComputable) {
e.config = config;
notifyProgress(getNotifyEvent(e));
}
}, false);
};
};
}
function uploadWithAngular() {
$http(config).then(function (r) {
if (resumeSupported && config._chunkSize && !config._finished && config._file) {
var fileSize = config._file && config._file.size || 0;
notifyProgress({
loaded: Math.min(config._end, fileSize),
total: fileSize,
config: config,
type: 'progress'
}
);
upload.upload(config, true);
} else {
if (config._finished) delete config._finished;
deferred.resolve(r);
}
}, function (e) {
deferred.reject(e);
}, function (n) {
deferred.notify(n);
}
);
}
if (!resumeSupported) {
uploadWithAngular();
} else if (config._chunkSize && config._end && !config._finished) {
config._start = config._end;
config._end += config._chunkSize;
uploadWithAngular();
} else if (config.resumeSizeUrl) {
$http.get(config.resumeSizeUrl).then(function (resp) {
if (config.resumeSizeResponseReader) {
config._start = config.resumeSizeResponseReader(resp.data);
} else {
config._start = parseInt((resp.data.size == null ? resp.data : resp.data.size).toString());
}
if (config._chunkSize) {
config._end = config._start + config._chunkSize;
}
uploadWithAngular();
}, function (e) {
throw e;
});
} else if (config.resumeSize) {
config.resumeSize().then(function (size) {
config._start = size;
if (config._chunkSize) {
config._end = config._start + config._chunkSize;
}
uploadWithAngular();
}, function (e) {
throw e;
});
} else {
if (config._chunkSize) {
config._start = 0;
config._end = config._start + config._chunkSize;
}
uploadWithAngular();
}
promise.success = function (fn) {
promise.then(function (response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function (fn) {
promise.then(null, function (response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.progress = function (fn) {
promise.progressFunc = fn;
promise.then(null, null, function (n) {
fn(n);
});
return promise;
};
promise.abort = promise.pause = function () {
if (config.__XHR) {
$timeout(function () {
config.__XHR.abort();
});
}
return promise;
};
promise.xhr = function (fn) {
config.xhrFn = (function (origXhrFn) {
return function () {
if (origXhrFn) origXhrFn.apply(promise, arguments);
fn.apply(promise, arguments);
};
})(config.xhrFn);
return promise;
};
upload.promisesCount++;
if (promise['finally'] && promise['finally'] instanceof Function) {
promise['finally'](function () {
upload.promisesCount--;
});
}
return promise;
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
sendHttp
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function notifyProgress(e) {
if (deferred.notify) {
deferred.notify(e);
}
if (promise.progressFunc) {
$timeout(function () {
promise.progressFunc(e);
});
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
notifyProgress
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function getNotifyEvent(n) {
if (config._start != null && resumeSupported) {
return {
loaded: n.loaded + config._start,
total: (config._file && config._file.size) || n.total,
type: n.type, config: config,
lengthComputable: true, target: n.target
};
} else {
return n;
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
getNotifyEvent
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function uploadWithAngular() {
$http(config).then(function (r) {
if (resumeSupported && config._chunkSize && !config._finished && config._file) {
var fileSize = config._file && config._file.size || 0;
notifyProgress({
loaded: Math.min(config._end, fileSize),
total: fileSize,
config: config,
type: 'progress'
}
);
upload.upload(config, true);
} else {
if (config._finished) delete config._finished;
deferred.resolve(r);
}
}, function (e) {
deferred.reject(e);
}, function (n) {
deferred.notify(n);
}
);
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
uploadWithAngular
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function copy(obj) {
var clone = {};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = obj[key];
}
}
return clone;
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
copy
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function toResumeFile(file, formData) {
if (file._ngfBlob) return file;
config._file = config._file || file;
if (config._start != null && resumeSupported) {
if (config._end && config._end >= file.size) {
config._finished = true;
config._end = file.size;
}
var slice = file.slice(config._start, config._end || file.size);
slice.name = file.name;
slice.ngfName = file.ngfName;
if (config._chunkSize) {
formData.append('_chunkSize', config._chunkSize);
formData.append('_currentChunkSize', config._end - config._start);
formData.append('_chunkNumber', Math.floor(config._start / config._chunkSize));
formData.append('_totalSize', config._file.size);
}
return slice;
}
return file;
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
toResumeFile
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function addFieldToFormData(formData, val, key) {
if (val !== undefined) {
if (angular.isDate(val)) {
val = val.toISOString();
}
if (angular.isString(val)) {
formData.append(key, val);
} else if (upload.isFile(val)) {
var file = toResumeFile(val, formData);
var split = key.split(',');
if (split[1]) {
file.ngfName = split[1].replace(/^\s+|\s+$/g, '');
key = split[0];
}
config._fileKey = config._fileKey || key;
formData.append(key, file, file.ngfName || file.name);
} else {
if (angular.isObject(val)) {
if (val.$$ngfCircularDetection) throw 'ngFileUpload: Circular reference in config.data. Make sure specified data for Upload.upload() has no circular reference: ' + key;
val.$$ngfCircularDetection = true;
try {
for (var k in val) {
if (val.hasOwnProperty(k) && k !== '$$ngfCircularDetection') {
var objectKey = config.objectKey == null ? '[i]' : config.objectKey;
if (val.length && parseInt(k) > -1) {
objectKey = config.arrayKey == null ? objectKey : config.arrayKey;
}
addFieldToFormData(formData, val[k], key + objectKey.replace(/[ik]/g, k));
}
}
} finally {
delete val.$$ngfCircularDetection;
}
} else {
formData.append(key, val);
}
}
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
addFieldToFormData
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function digestConfig() {
config._chunkSize = upload.translateScalars(config.resumeChunkSize);
config._chunkSize = config._chunkSize ? parseInt(config._chunkSize.toString()) : null;
config.headers = config.headers || {};
config.headers['Content-Type'] = undefined;
config.transformRequest = config.transformRequest ?
(angular.isArray(config.transformRequest) ?
config.transformRequest : [config.transformRequest]) : [];
config.transformRequest.push(function (data) {
var formData = new window.FormData(), key;
data = data || config.fields || {};
if (config.file) {
data.file = config.file;
}
for (key in data) {
if (data.hasOwnProperty(key)) {
var val = data[key];
if (config.formDataAppender) {
config.formDataAppender(formData, key, val);
} else {
addFieldToFormData(formData, val, key);
}
}
}
return formData;
});
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
digestConfig
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function applyExifRotations(files, attr, scope) {
var promises = [upload.emptyPromise()];
angular.forEach(files, function (f, i) {
if (f.type.indexOf('image/jpeg') === 0 && upload.attrGetter('ngfFixOrientation', attr, scope, {$file: f})) {
promises.push(upload.happyPromise(upload.applyExifRotation(f), f).then(function (fixedFile) {
files.splice(i, 1, fixedFile);
}));
}
});
return $q.all(promises);
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
applyExifRotations
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function resizeFile(files, attr, scope, ngModel) {
var resizeVal = upload.attrGetter('ngfResize', attr, scope);
if (!resizeVal || !upload.isResizeSupported() || !files.length) return upload.emptyPromise();
if (resizeVal instanceof Function) {
var defer = $q.defer();
return resizeVal(files).then(function (p) {
resizeWithParams(p, files, attr, scope, ngModel).then(function (r) {
defer.resolve(r);
}, function (e) {
defer.reject(e);
});
}, function (e) {
defer.reject(e);
});
} else {
return resizeWithParams(resizeVal, files, attr, scope, ngModel);
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
resizeFile
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function resizeWithParams(params, files, attr, scope, ngModel) {
var promises = [upload.emptyPromise()];
function handleFile(f, i) {
if (f.type.indexOf('image') === 0) {
if (params.pattern && !upload.validatePattern(f, params.pattern)) return;
params.resizeIf = function (width, height) {
return upload.attrGetter('ngfResizeIf', attr, scope,
{$width: width, $height: height, $file: f});
};
var promise = upload.resize(f, params);
promises.push(promise);
promise.then(function (resizedFile) {
files.splice(i, 1, resizedFile);
}, function (e) {
f.$error = 'resize';
(f.$errorMessages = (f.$errorMessages || {})).resize = true;
f.$errorParam = (e ? (e.message ? e.message : e) + ': ' : '') + (f && f.name);
ngModel.$ngfValidations.push({name: 'resize', valid: false});
upload.applyModelValidation(ngModel, files);
});
}
}
for (var i = 0; i < files.length; i++) {
handleFile(files[i], i);
}
return $q.all(promises);
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
resizeWithParams
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function handleFile(f, i) {
if (f.type.indexOf('image') === 0) {
if (params.pattern && !upload.validatePattern(f, params.pattern)) return;
params.resizeIf = function (width, height) {
return upload.attrGetter('ngfResizeIf', attr, scope,
{$width: width, $height: height, $file: f});
};
var promise = upload.resize(f, params);
promises.push(promise);
promise.then(function (resizedFile) {
files.splice(i, 1, resizedFile);
}, function (e) {
f.$error = 'resize';
(f.$errorMessages = (f.$errorMessages || {})).resize = true;
f.$errorParam = (e ? (e.message ? e.message : e) + ': ' : '') + (f && f.name);
ngModel.$ngfValidations.push({name: 'resize', valid: false});
upload.applyModelValidation(ngModel, files);
});
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
handleFile
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function update(files, invalidFiles, newFiles, dupFiles, isSingleModel) {
attr.$$ngfPrevValidFiles = files;
attr.$$ngfPrevInvalidFiles = invalidFiles;
var file = files && files.length ? files[0] : null;
var invalidFile = invalidFiles && invalidFiles.length ? invalidFiles[0] : null;
if (ngModel) {
upload.applyModelValidation(ngModel, files);
ngModel.$setViewValue(isSingleModel ? file : files);
}
if (fileChange) {
$parse(fileChange)(scope, {
$files: files,
$file: file,
$newFiles: newFiles,
$duplicateFiles: dupFiles,
$invalidFiles: invalidFiles,
$invalidFile: invalidFile,
$event: evt
});
}
var invalidModel = upload.attrGetter('ngfModelInvalid', attr);
if (invalidModel) {
$timeout(function () {
$parse(invalidModel).assign(scope, isSingleModel ? invalidFile : invalidFiles);
});
}
$timeout(function () {
// scope apply changes
});
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
update
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function removeDuplicates() {
function equals(f1, f2) {
return f1.name === f2.name && (f1.$ngfOrigSize || f1.size) === (f2.$ngfOrigSize || f2.size) &&
f1.type === f2.type;
}
function isInPrevFiles(f) {
var j;
for (j = 0; j < prevValidFiles.length; j++) {
if (equals(f, prevValidFiles[j])) {
return true;
}
}
for (j = 0; j < prevInvalidFiles.length; j++) {
if (equals(f, prevInvalidFiles[j])) {
return true;
}
}
return false;
}
if (files) {
allNewFiles = [];
dupFiles = [];
for (var i = 0; i < files.length; i++) {
if (isInPrevFiles(files[i])) {
dupFiles.push(files[i]);
} else {
allNewFiles.push(files[i]);
}
}
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
removeDuplicates
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function equals(f1, f2) {
return f1.name === f2.name && (f1.$ngfOrigSize || f1.size) === (f2.$ngfOrigSize || f2.size) &&
f1.type === f2.type;
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
equals
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function isInPrevFiles(f) {
var j;
for (j = 0; j < prevValidFiles.length; j++) {
if (equals(f, prevValidFiles[j])) {
return true;
}
}
for (j = 0; j < prevInvalidFiles.length; j++) {
if (equals(f, prevInvalidFiles[j])) {
return true;
}
}
return false;
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
isInPrevFiles
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function toArray(v) {
return angular.isArray(v) ? v : [v];
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
toArray
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function resizeAndUpdate() {
function updateModel() {
$timeout(function () {
update(keep ? prevValidFiles.concat(valids) : valids,
keep ? prevInvalidFiles.concat(invalids) : invalids,
files, dupFiles, isSingleModel);
}, options && options.debounce ? options.debounce.change || options.debounce : 0);
}
var resizingFiles = validateAfterResize ? allNewFiles : valids;
resizeFile(resizingFiles, attr, scope, ngModel).then(function () {
if (validateAfterResize) {
upload.validate(allNewFiles, keep ? prevValidFiles.length : 0, ngModel, attr, scope)
.then(function (validationResult) {
valids = validationResult.validsFiles;
invalids = validationResult.invalidsFiles;
updateModel();
});
} else {
updateModel();
}
}, function () {
for (var i = 0; i < resizingFiles.length; i++) {
var f = resizingFiles[i];
if (f.$error === 'resize') {
var index = valids.indexOf(f);
if (index > -1) {
valids.splice(index, 1);
invalids.push(f);
}
updateModel();
}
}
});
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
resizeAndUpdate
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function updateModel() {
$timeout(function () {
update(keep ? prevValidFiles.concat(valids) : valids,
keep ? prevInvalidFiles.concat(invalids) : invalids,
files, dupFiles, isSingleModel);
}, options && options.debounce ? options.debounce.change || options.debounce : 0);
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
updateModel
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function isDelayedClickSupported(ua) {
// fix for android native browser < 4.4 and safari windows
var m = ua.match(/Android[^\d]*(\d+)\.(\d+)/);
if (m && m.length > 2) {
var v = Upload.defaults.androidFixMinorVersion || 4;
return parseInt(m[1]) < 4 || (parseInt(m[1]) === v && parseInt(m[2]) < v);
}
// safari on windows
return ua.indexOf('Chrome') === -1 && /.*Windows.*Safari.*/.test(ua);
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
isDelayedClickSupported
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function linkFileSelect(scope, elem, attr, ngModel, $parse, $timeout, $compile, upload) {
/** @namespace attr.ngfSelect */
/** @namespace attr.ngfChange */
/** @namespace attr.ngModel */
/** @namespace attr.ngfModelOptions */
/** @namespace attr.ngfMultiple */
/** @namespace attr.ngfCapture */
/** @namespace attr.ngfValidate */
/** @namespace attr.ngfKeep */
var attrGetter = function (name, scope) {
return upload.attrGetter(name, attr, scope);
};
function isInputTypeFile() {
return elem[0].tagName.toLowerCase() === 'input' && attr.type && attr.type.toLowerCase() === 'file';
}
function fileChangeAttr() {
return attrGetter('ngfChange') || attrGetter('ngfSelect');
}
function changeFn(evt) {
if (upload.shouldUpdateOn('change', attr, scope)) {
var fileList = evt.__files_ || (evt.target && evt.target.files), files = [];
/* Handle duplicate call in IE11 */
if (!fileList) return;
for (var i = 0; i < fileList.length; i++) {
files.push(fileList[i]);
}
upload.updateModel(ngModel, attr, scope, fileChangeAttr(),
files.length ? files : null, evt);
}
}
upload.registerModelChangeValidator(ngModel, attr, scope);
var unwatches = [];
if (attrGetter('ngfMultiple')) {
unwatches.push(scope.$watch(attrGetter('ngfMultiple'), function () {
fileElem.attr('multiple', attrGetter('ngfMultiple', scope));
}));
}
if (attrGetter('ngfCapture')) {
unwatches.push(scope.$watch(attrGetter('ngfCapture'), function () {
fileElem.attr('capture', attrGetter('ngfCapture', scope));
}));
}
if (attrGetter('ngfAccept')) {
unwatches.push(scope.$watch(attrGetter('ngfAccept'), function () {
fileElem.attr('accept', attrGetter('ngfAccept', scope));
}));
}
unwatches.push(attr.$observe('accept', function () {
fileElem.attr('accept', attrGetter('accept'));
}));
function bindAttrToFileInput(fileElem, label) {
function updateId(val) {
fileElem.attr('id', 'ngf-' + val);
label.attr('id', 'ngf-label-' + val);
}
for (var i = 0; i < elem[0].attributes.length; i++) {
var attribute = elem[0].attributes[i];
if (attribute.name !== 'type' && attribute.name !== 'class' && attribute.name !== 'style') {
if (attribute.name === 'id') {
updateId(attribute.value);
unwatches.push(attr.$observe('id', updateId));
} else {
fileElem.attr(attribute.name, (!attribute.value && (attribute.name === 'required' ||
attribute.name === 'multiple')) ? attribute.name : attribute.value);
}
}
}
}
function createFileInput() {
if (isInputTypeFile()) {
return elem;
}
var fileElem = angular.element('<input type="file">');
var label = angular.element('<label>upload</label>');
label.css('visibility', 'hidden').css('position', 'absolute').css('overflow', 'hidden')
.css('width', '0px').css('height', '0px').css('border', 'none')
.css('margin', '0px').css('padding', '0px').attr('tabindex', '-1');
bindAttrToFileInput(fileElem, label);
generatedElems.push({el: elem, ref: label});
document.body.appendChild(label.append(fileElem)[0]);
return fileElem;
}
function clickHandler(evt) {
if (elem.attr('disabled')) return false;
if (attrGetter('ngfSelectDisabled', scope)) return;
var r = detectSwipe(evt);
// prevent the click if it is a swipe
if (r != null) return r;
resetModel(evt);
// fix for md when the element is removed from the DOM and added back #460
try {
if (!isInputTypeFile() && !document.body.contains(fileElem[0])) {
generatedElems.push({el: elem, ref: fileElem.parent()});
document.body.appendChild(fileElem.parent()[0]);
fileElem.bind('change', changeFn);
}
} catch (e) {/*ignore*/
}
if (isDelayedClickSupported(navigator.userAgent)) {
setTimeout(function () {
fileElem[0].click();
}, 0);
} else {
fileElem[0].click();
}
return false;
}
var initialTouchStartY = 0;
var initialTouchStartX = 0;
function detectSwipe(evt) {
var touches = evt.changedTouches || (evt.originalEvent && evt.originalEvent.changedTouches);
if (touches) {
if (evt.type === 'touchstart') {
initialTouchStartX = touches[0].clientX;
initialTouchStartY = touches[0].clientY;
return true; // don't block event default
} else {
// prevent scroll from triggering event
if (evt.type === 'touchend') {
var currentX = touches[0].clientX;
var currentY = touches[0].clientY;
if ((Math.abs(currentX - initialTouchStartX) > 20) ||
(Math.abs(currentY - initialTouchStartY) > 20)) {
evt.stopPropagation();
evt.preventDefault();
return false;
}
}
return true;
}
}
}
var fileElem = elem;
function resetModel(evt) {
if (upload.shouldUpdateOn('click', attr, scope) && fileElem.val()) {
fileElem.val(null);
upload.updateModel(ngModel, attr, scope, fileChangeAttr(), null, evt, true);
}
}
if (!isInputTypeFile()) {
fileElem = createFileInput();
}
fileElem.bind('change', changeFn);
if (!isInputTypeFile()) {
elem.bind('click touchstart touchend', clickHandler);
} else {
elem.bind('click', resetModel);
}
function ie10SameFileSelectFix(evt) {
if (fileElem && !fileElem.attr('__ngf_ie10_Fix_')) {
if (!fileElem[0].parentNode) {
fileElem = null;
return;
}
evt.preventDefault();
evt.stopPropagation();
fileElem.unbind('click');
var clone = fileElem.clone();
fileElem.replaceWith(clone);
fileElem = clone;
fileElem.attr('__ngf_ie10_Fix_', 'true');
fileElem.bind('change', changeFn);
fileElem.bind('click', ie10SameFileSelectFix);
fileElem[0].click();
return false;
} else {
fileElem.removeAttr('__ngf_ie10_Fix_');
}
}
if (navigator.appVersion.indexOf('MSIE 10') !== -1) {
fileElem.bind('click', ie10SameFileSelectFix);
}
if (ngModel) ngModel.$formatters.push(function (val) {
if (val == null || val.length === 0) {
if (fileElem.val()) {
fileElem.val(null);
}
}
return val;
});
scope.$on('$destroy', function () {
if (!isInputTypeFile()) fileElem.parent().remove();
angular.forEach(unwatches, function (unwatch) {
unwatch();
});
});
$timeout(function () {
for (var i = 0; i < generatedElems.length; i++) {
var g = generatedElems[i];
if (!document.body.contains(g.el[0])) {
generatedElems.splice(i, 1);
g.ref.remove();
}
}
});
if (window.FileAPI && window.FileAPI.ngfFixIE) {
window.FileAPI.ngfFixIE(elem, fileElem, changeFn);
}
}
|
!
AngularJS file upload directives and services. Supoorts: file upload/drop/paste, resume, cancel/abort,
progress, resize, thumbnail, preview, validation and CORS
@author Danial <[email protected]>
@version 12.2.13
|
linkFileSelect
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
calculateAspectRatioFit = function (srcWidth, srcHeight, maxWidth, maxHeight, centerCrop) {
var ratio = centerCrop ? Math.max(maxWidth / srcWidth, maxHeight / srcHeight) :
Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
return {
width: srcWidth * ratio, height: srcHeight * ratio,
marginX: srcWidth * ratio - maxWidth, marginY: srcHeight * ratio - maxHeight
};
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
calculateAspectRatioFit
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
resize = function (imagen, width, height, quality, type, ratio, centerCrop, resizeIf) {
var deferred = $q.defer();
var canvasElement = document.createElement('canvas');
var imageElement = document.createElement('img');
imageElement.setAttribute('style', 'visibility:hidden;position:fixed;z-index:-100000');
document.body.appendChild(imageElement);
imageElement.onload = function () {
var imgWidth = imageElement.width, imgHeight = imageElement.height;
imageElement.parentNode.removeChild(imageElement);
if (resizeIf != null && resizeIf(imgWidth, imgHeight) === false) {
deferred.reject('resizeIf');
return;
}
try {
if (ratio) {
var ratioFloat = upload.ratioToFloat(ratio);
var imgRatio = imgWidth / imgHeight;
if (imgRatio < ratioFloat) {
width = imgWidth;
height = width / ratioFloat;
} else {
height = imgHeight;
width = height * ratioFloat;
}
}
if (!width) {
width = imgWidth;
}
if (!height) {
height = imgHeight;
}
var dimensions = calculateAspectRatioFit(imgWidth, imgHeight, width, height, centerCrop);
canvasElement.width = Math.min(dimensions.width, width);
canvasElement.height = Math.min(dimensions.height, height);
var context = canvasElement.getContext('2d');
context.drawImage(imageElement,
Math.min(0, -dimensions.marginX / 2), Math.min(0, -dimensions.marginY / 2),
dimensions.width, dimensions.height);
deferred.resolve(canvasElement.toDataURL(type || 'image/WebP', quality || 0.934));
} catch (e) {
deferred.reject(e);
}
};
imageElement.onerror = function () {
imageElement.parentNode.removeChild(imageElement);
deferred.reject();
};
imageElement.src = imagen;
return deferred.promise;
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
resize
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function linkDrop(scope, elem, attr, ngModel, $parse, $timeout, $window, upload, $http, $q) {
var available = dropAvailable();
var attrGetter = function (name, scope, params) {
return upload.attrGetter(name, attr, scope, params);
};
if (attrGetter('dropAvailable')) {
$timeout(function () {
if (scope[attrGetter('dropAvailable')]) {
scope[attrGetter('dropAvailable')].value = available;
} else {
scope[attrGetter('dropAvailable')] = available;
}
});
}
if (!available) {
if (attrGetter('ngfHideOnDropNotAvailable', scope) === true) {
elem.css('display', 'none');
}
return;
}
function isDisabled() {
return elem.attr('disabled') || attrGetter('ngfDropDisabled', scope);
}
if (attrGetter('ngfSelect') == null) {
upload.registerModelChangeValidator(ngModel, attr, scope);
}
var leaveTimeout = null;
var stopPropagation = $parse(attrGetter('ngfStopPropagation'));
var dragOverDelay = 1;
var actualDragOverClass;
elem[0].addEventListener('dragover', function (evt) {
if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
evt.preventDefault();
if (stopPropagation(scope)) evt.stopPropagation();
// handling dragover events from the Chrome download bar
if (navigator.userAgent.indexOf('Chrome') > -1) {
var b = evt.dataTransfer.effectAllowed;
evt.dataTransfer.dropEffect = ('move' === b || 'linkMove' === b) ? 'move' : 'copy';
}
$timeout.cancel(leaveTimeout);
if (!actualDragOverClass) {
actualDragOverClass = 'C';
calculateDragOverClass(scope, attr, evt, function (clazz) {
actualDragOverClass = clazz;
elem.addClass(actualDragOverClass);
attrGetter('ngfDrag', scope, {$isDragging: true, $class: actualDragOverClass, $event: evt});
});
}
}, false);
elem[0].addEventListener('dragenter', function (evt) {
if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
evt.preventDefault();
if (stopPropagation(scope)) evt.stopPropagation();
}, false);
elem[0].addEventListener('dragleave', function (evt) {
if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
evt.preventDefault();
if (stopPropagation(scope)) evt.stopPropagation();
leaveTimeout = $timeout(function () {
if (actualDragOverClass) elem.removeClass(actualDragOverClass);
actualDragOverClass = null;
attrGetter('ngfDrag', scope, {$isDragging: false, $event: evt});
}, dragOverDelay || 100);
}, false);
elem[0].addEventListener('drop', function (evt) {
if (isDisabled() || !upload.shouldUpdateOn('drop', attr, scope)) return;
evt.preventDefault();
if (stopPropagation(scope)) evt.stopPropagation();
if (actualDragOverClass) elem.removeClass(actualDragOverClass);
actualDragOverClass = null;
extractFilesAndUpdateModel(evt.dataTransfer, evt, 'dropUrl');
}, false);
elem[0].addEventListener('paste', function (evt) {
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1 &&
attrGetter('ngfEnableFirefoxPaste', scope)) {
evt.preventDefault();
}
if (isDisabled() || !upload.shouldUpdateOn('paste', attr, scope)) return;
extractFilesAndUpdateModel(evt.clipboardData || evt.originalEvent.clipboardData, evt, 'pasteUrl');
}, false);
if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1 &&
attrGetter('ngfEnableFirefoxPaste', scope)) {
elem.attr('contenteditable', true);
elem.on('keypress', function (e) {
if (!e.metaKey && !e.ctrlKey) {
e.preventDefault();
}
});
}
function extractFilesAndUpdateModel(source, evt, updateOnType) {
if (!source) return;
// html needs to be calculated on the same process otherwise the data will be wiped
// after promise resolve or setTimeout.
var html;
try {
html = source && source.getData && source.getData('text/html');
} catch (e) {/* Fix IE11 that throw error calling getData */
}
extractFiles(source.items, source.files, attrGetter('ngfAllowDir', scope) !== false,
attrGetter('multiple') || attrGetter('ngfMultiple', scope)).then(function (files) {
if (files.length) {
updateModel(files, evt);
} else {
extractFilesFromHtml(updateOnType, html).then(function (files) {
updateModel(files, evt);
});
}
});
}
function updateModel(files, evt) {
upload.updateModel(ngModel, attr, scope, attrGetter('ngfChange') || attrGetter('ngfDrop'), files, evt);
}
function extractFilesFromHtml(updateOn, html) {
if (!upload.shouldUpdateOn(updateOn, attr, scope) || typeof html !== 'string') return upload.rejectPromise([]);
var urls = [];
html.replace(/<(img src|img [^>]* src) *=\"([^\"]*)\"/gi, function (m, n, src) {
urls.push(src);
});
var promises = [], files = [];
if (urls.length) {
angular.forEach(urls, function (url) {
promises.push(upload.urlToBlob(url).then(function (blob) {
files.push(blob);
}));
});
var defer = $q.defer();
$q.all(promises).then(function () {
defer.resolve(files);
}, function (e) {
defer.reject(e);
});
return defer.promise;
}
return upload.emptyPromise();
}
function calculateDragOverClass(scope, attr, evt, callback) {
var obj = attrGetter('ngfDragOverClass', scope, {$event: evt}), dClass = 'dragover';
if (angular.isString(obj)) {
dClass = obj;
} else if (obj) {
if (obj.delay) dragOverDelay = obj.delay;
if (obj.accept || obj.reject) {
var items = evt.dataTransfer.items;
if (items == null || !items.length) {
dClass = obj.accept;
} else {
var pattern = obj.pattern || attrGetter('ngfPattern', scope, {$event: evt});
var len = items.length;
while (len--) {
if (!upload.validatePattern(items[len], pattern)) {
dClass = obj.reject;
break;
} else {
dClass = obj.accept;
}
}
}
}
}
callback(dClass);
}
function extractFiles(items, fileList, allowDir, multiple) {
var maxFiles = upload.getValidationAttr(attr, scope, 'maxFiles');
if (maxFiles == null) {
maxFiles = Number.MAX_VALUE;
}
var maxTotalSize = upload.getValidationAttr(attr, scope, 'maxTotalSize');
if (maxTotalSize == null) {
maxTotalSize = Number.MAX_VALUE;
}
var includeDir = attrGetter('ngfIncludeDir', scope);
var files = [], totalSize = 0;
function traverseFileTree(entry, path) {
var defer = $q.defer();
if (entry != null) {
if (entry.isDirectory) {
var promises = [upload.emptyPromise()];
if (includeDir) {
var file = {type: 'directory'};
file.name = file.path = (path || '') + entry.name;
files.push(file);
}
var dirReader = entry.createReader();
var entries = [];
var readEntries = function () {
dirReader.readEntries(function (results) {
try {
if (!results.length) {
angular.forEach(entries.slice(0), function (e) {
if (files.length <= maxFiles && totalSize <= maxTotalSize) {
promises.push(traverseFileTree(e, (path ? path : '') + entry.name + '/'));
}
});
$q.all(promises).then(function () {
defer.resolve();
}, function (e) {
defer.reject(e);
});
} else {
entries = entries.concat(Array.prototype.slice.call(results || [], 0));
readEntries();
}
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
};
readEntries();
} else {
entry.file(function (file) {
try {
file.path = (path ? path : '') + file.name;
if (includeDir) {
file = upload.rename(file, file.path);
}
files.push(file);
totalSize += file.size;
defer.resolve();
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
}
}
return defer.promise;
}
var promises = [upload.emptyPromise()];
if (items && items.length > 0 && $window.location.protocol !== 'file:') {
for (var i = 0; i < items.length; i++) {
if (items[i].webkitGetAsEntry && items[i].webkitGetAsEntry() && items[i].webkitGetAsEntry().isDirectory) {
var entry = items[i].webkitGetAsEntry();
if (entry.isDirectory && !allowDir) {
continue;
}
if (entry != null) {
promises.push(traverseFileTree(entry));
}
} else {
var f = items[i].getAsFile();
if (f != null) {
files.push(f);
totalSize += f.size;
}
}
if (files.length > maxFiles || totalSize > maxTotalSize ||
(!multiple && files.length > 0)) break;
}
} else {
if (fileList != null) {
for (var j = 0; j < fileList.length; j++) {
var file = fileList.item(j);
if (file.type || file.size > 0) {
files.push(file);
totalSize += file.size;
}
if (files.length > maxFiles || totalSize > maxTotalSize ||
(!multiple && files.length > 0)) break;
}
}
}
var defer = $q.defer();
$q.all(promises).then(function () {
if (!multiple && !includeDir && files.length) {
var i = 0;
while (files[i] && files[i].type === 'directory') i++;
defer.resolve([files[i]]);
} else {
defer.resolve(files);
}
}, function (e) {
defer.reject(e);
});
return defer.promise;
}
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
linkDrop
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
attrGetter = function (name, scope, params) {
return upload.attrGetter(name, attr, scope, params);
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
attrGetter
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function isDisabled() {
return elem.attr('disabled') || attrGetter('ngfDropDisabled', scope);
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
isDisabled
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function extractFilesAndUpdateModel(source, evt, updateOnType) {
if (!source) return;
// html needs to be calculated on the same process otherwise the data will be wiped
// after promise resolve or setTimeout.
var html;
try {
html = source && source.getData && source.getData('text/html');
} catch (e) {/* Fix IE11 that throw error calling getData */
}
extractFiles(source.items, source.files, attrGetter('ngfAllowDir', scope) !== false,
attrGetter('multiple') || attrGetter('ngfMultiple', scope)).then(function (files) {
if (files.length) {
updateModel(files, evt);
} else {
extractFilesFromHtml(updateOnType, html).then(function (files) {
updateModel(files, evt);
});
}
});
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
extractFilesAndUpdateModel
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function updateModel(files, evt) {
upload.updateModel(ngModel, attr, scope, attrGetter('ngfChange') || attrGetter('ngfDrop'), files, evt);
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
updateModel
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function extractFilesFromHtml(updateOn, html) {
if (!upload.shouldUpdateOn(updateOn, attr, scope) || typeof html !== 'string') return upload.rejectPromise([]);
var urls = [];
html.replace(/<(img src|img [^>]* src) *=\"([^\"]*)\"/gi, function (m, n, src) {
urls.push(src);
});
var promises = [], files = [];
if (urls.length) {
angular.forEach(urls, function (url) {
promises.push(upload.urlToBlob(url).then(function (blob) {
files.push(blob);
}));
});
var defer = $q.defer();
$q.all(promises).then(function () {
defer.resolve(files);
}, function (e) {
defer.reject(e);
});
return defer.promise;
}
return upload.emptyPromise();
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
extractFilesFromHtml
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function calculateDragOverClass(scope, attr, evt, callback) {
var obj = attrGetter('ngfDragOverClass', scope, {$event: evt}), dClass = 'dragover';
if (angular.isString(obj)) {
dClass = obj;
} else if (obj) {
if (obj.delay) dragOverDelay = obj.delay;
if (obj.accept || obj.reject) {
var items = evt.dataTransfer.items;
if (items == null || !items.length) {
dClass = obj.accept;
} else {
var pattern = obj.pattern || attrGetter('ngfPattern', scope, {$event: evt});
var len = items.length;
while (len--) {
if (!upload.validatePattern(items[len], pattern)) {
dClass = obj.reject;
break;
} else {
dClass = obj.accept;
}
}
}
}
}
callback(dClass);
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
calculateDragOverClass
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function extractFiles(items, fileList, allowDir, multiple) {
var maxFiles = upload.getValidationAttr(attr, scope, 'maxFiles');
if (maxFiles == null) {
maxFiles = Number.MAX_VALUE;
}
var maxTotalSize = upload.getValidationAttr(attr, scope, 'maxTotalSize');
if (maxTotalSize == null) {
maxTotalSize = Number.MAX_VALUE;
}
var includeDir = attrGetter('ngfIncludeDir', scope);
var files = [], totalSize = 0;
function traverseFileTree(entry, path) {
var defer = $q.defer();
if (entry != null) {
if (entry.isDirectory) {
var promises = [upload.emptyPromise()];
if (includeDir) {
var file = {type: 'directory'};
file.name = file.path = (path || '') + entry.name;
files.push(file);
}
var dirReader = entry.createReader();
var entries = [];
var readEntries = function () {
dirReader.readEntries(function (results) {
try {
if (!results.length) {
angular.forEach(entries.slice(0), function (e) {
if (files.length <= maxFiles && totalSize <= maxTotalSize) {
promises.push(traverseFileTree(e, (path ? path : '') + entry.name + '/'));
}
});
$q.all(promises).then(function () {
defer.resolve();
}, function (e) {
defer.reject(e);
});
} else {
entries = entries.concat(Array.prototype.slice.call(results || [], 0));
readEntries();
}
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
};
readEntries();
} else {
entry.file(function (file) {
try {
file.path = (path ? path : '') + file.name;
if (includeDir) {
file = upload.rename(file, file.path);
}
files.push(file);
totalSize += file.size;
defer.resolve();
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
}
}
return defer.promise;
}
var promises = [upload.emptyPromise()];
if (items && items.length > 0 && $window.location.protocol !== 'file:') {
for (var i = 0; i < items.length; i++) {
if (items[i].webkitGetAsEntry && items[i].webkitGetAsEntry() && items[i].webkitGetAsEntry().isDirectory) {
var entry = items[i].webkitGetAsEntry();
if (entry.isDirectory && !allowDir) {
continue;
}
if (entry != null) {
promises.push(traverseFileTree(entry));
}
} else {
var f = items[i].getAsFile();
if (f != null) {
files.push(f);
totalSize += f.size;
}
}
if (files.length > maxFiles || totalSize > maxTotalSize ||
(!multiple && files.length > 0)) break;
}
} else {
if (fileList != null) {
for (var j = 0; j < fileList.length; j++) {
var file = fileList.item(j);
if (file.type || file.size > 0) {
files.push(file);
totalSize += file.size;
}
if (files.length > maxFiles || totalSize > maxTotalSize ||
(!multiple && files.length > 0)) break;
}
}
}
var defer = $q.defer();
$q.all(promises).then(function () {
if (!multiple && !includeDir && files.length) {
var i = 0;
while (files[i] && files[i].type === 'directory') i++;
defer.resolve([files[i]]);
} else {
defer.resolve(files);
}
}, function (e) {
defer.reject(e);
});
return defer.promise;
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
extractFiles
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function traverseFileTree(entry, path) {
var defer = $q.defer();
if (entry != null) {
if (entry.isDirectory) {
var promises = [upload.emptyPromise()];
if (includeDir) {
var file = {type: 'directory'};
file.name = file.path = (path || '') + entry.name;
files.push(file);
}
var dirReader = entry.createReader();
var entries = [];
var readEntries = function () {
dirReader.readEntries(function (results) {
try {
if (!results.length) {
angular.forEach(entries.slice(0), function (e) {
if (files.length <= maxFiles && totalSize <= maxTotalSize) {
promises.push(traverseFileTree(e, (path ? path : '') + entry.name + '/'));
}
});
$q.all(promises).then(function () {
defer.resolve();
}, function (e) {
defer.reject(e);
});
} else {
entries = entries.concat(Array.prototype.slice.call(results || [], 0));
readEntries();
}
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
};
readEntries();
} else {
entry.file(function (file) {
try {
file.path = (path ? path : '') + file.name;
if (includeDir) {
file = upload.rename(file, file.path);
}
files.push(file);
totalSize += file.size;
defer.resolve();
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
}
}
return defer.promise;
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
traverseFileTree
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
readEntries = function () {
dirReader.readEntries(function (results) {
try {
if (!results.length) {
angular.forEach(entries.slice(0), function (e) {
if (files.length <= maxFiles && totalSize <= maxTotalSize) {
promises.push(traverseFileTree(e, (path ? path : '') + entry.name + '/'));
}
});
$q.all(promises).then(function () {
defer.resolve();
}, function (e) {
defer.reject(e);
});
} else {
entries = entries.concat(Array.prototype.slice.call(results || [], 0));
readEntries();
}
} catch (e) {
defer.reject(e);
}
}, function (e) {
defer.reject(e);
});
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
readEntries
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function dropAvailable() {
var div = document.createElement('div');
return ('draggable' in div) && ('ondrop' in div) && !/Edge\/12./i.test(navigator.userAgent);
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
dropAvailable
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function applyTransform(ctx, orientation, width, height) {
switch (orientation) {
case 2:
return ctx.transform(-1, 0, 0, 1, width, 0);
case 3:
return ctx.transform(-1, 0, 0, -1, width, height);
case 4:
return ctx.transform(1, 0, 0, -1, 0, height);
case 5:
return ctx.transform(0, 1, 1, 0, 0, 0);
case 6:
return ctx.transform(0, 1, -1, 0, height, 0);
case 7:
return ctx.transform(0, -1, -1, 0, height, width);
case 8:
return ctx.transform(0, -1, 1, 0, 0, width);
}
}
|
Conserve aspect ratio of the original region. Useful when shrinking/enlarging
images to fit into a certain area.
Source: http://stackoverflow.com/a/14731922
@param {Number} srcWidth Source area width
@param {Number} srcHeight Source area height
@param {Number} maxWidth Nestable area maximum available width
@param {Number} maxHeight Nestable area maximum available height
@return {Object} { width, height }
|
applyTransform
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.