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 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.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-file-upload.js
|
MIT
|
function addEvent(element, event, handler) {
if (element.addEventListener) {
element.addEventListener(event, handler, false);
} else if (element.attachEvent) {
element.attachEvent("on" + event, handler);
}
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
addEvent
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function imageHasData(img) {
return !!(img.exifdata);
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
imageHasData
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function base64ToArrayBuffer(base64, contentType) {
contentType = contentType || base64.match(/^data\:([^\;]+)\;base64,/mi)[1] || ''; // e.g. 'data:image/jpeg;base64,...' => 'image/jpeg'
base64 = base64.replace(/^data\:([^\;]+)\;base64,/gmi, '');
var binary = atob(base64);
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
view[i] = binary.charCodeAt(i);
}
return buffer;
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
base64ToArrayBuffer
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function objectURLToBlob(url, callback) {
var http = new XMLHttpRequest();
http.open("GET", url, true);
http.responseType = "blob";
http.onload = function(e) {
if (this.status == 200 || this.status === 0) {
callback(this.response);
}
};
http.send();
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
objectURLToBlob
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function getImageData(img, callback) {
function handleBinaryFile(binFile) {
var data = findEXIFinJPEG(binFile);
var iptcdata = findIPTCinJPEG(binFile);
img.exifdata = data || {};
img.iptcdata = iptcdata || {};
if (callback) {
callback.call(img);
}
}
if (img.src) {
if (/^data\:/i.test(img.src)) { // Data URI
var arrayBuffer = base64ToArrayBuffer(img.src);
handleBinaryFile(arrayBuffer);
} else if (/^blob\:/i.test(img.src)) { // Object URL
var fileReader = new FileReader();
fileReader.onload = function(e) {
handleBinaryFile(e.target.result);
};
objectURLToBlob(img.src, function (blob) {
fileReader.readAsArrayBuffer(blob);
});
} else {
var http = new XMLHttpRequest();
http.onload = function() {
if (this.status == 200 || this.status === 0) {
handleBinaryFile(http.response);
} else {
throw "Could not load image";
}
http = null;
};
http.open("GET", img.src, true);
http.responseType = "arraybuffer";
http.send(null);
}
} else if (window.FileReader && (img instanceof window.Blob || img instanceof window.File)) {
var fileReader = new FileReader();
fileReader.onload = function(e) {
if (debug) console.log("Got file of length " + e.target.result.byteLength);
handleBinaryFile(e.target.result);
};
fileReader.readAsArrayBuffer(img);
}
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
getImageData
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function handleBinaryFile(binFile) {
var data = findEXIFinJPEG(binFile);
var iptcdata = findIPTCinJPEG(binFile);
img.exifdata = data || {};
img.iptcdata = iptcdata || {};
if (callback) {
callback.call(img);
}
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
handleBinaryFile
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function findEXIFinJPEG(file) {
var dataView = new DataView(file);
if (debug) console.log("Got file of length " + file.byteLength);
if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
if (debug) console.log("Not a valid JPEG");
return false; // not a valid jpeg
}
var offset = 2,
length = file.byteLength,
marker;
while (offset < length) {
if (dataView.getUint8(offset) != 0xFF) {
if (debug) console.log("Not a valid marker at offset " + offset + ", found: " + dataView.getUint8(offset));
return false; // not a valid marker, something is wrong
}
marker = dataView.getUint8(offset + 1);
if (debug) console.log(marker);
// we could implement handling for other markers here,
// but we're only looking for 0xFFE1 for EXIF data
if (marker == 225) {
if (debug) console.log("Found 0xFFE1 marker");
return readEXIFData(dataView, offset + 4, dataView.getUint16(offset + 2) - 2);
// offset += 2 + file.getShortAt(offset+2, true);
} else {
offset += 2 + dataView.getUint16(offset+2);
}
}
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
findEXIFinJPEG
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function findIPTCinJPEG(file) {
var dataView = new DataView(file);
if (debug) console.log("Got file of length " + file.byteLength);
if ((dataView.getUint8(0) != 0xFF) || (dataView.getUint8(1) != 0xD8)) {
if (debug) console.log("Not a valid JPEG");
return false; // not a valid jpeg
}
var offset = 2,
length = file.byteLength;
var isFieldSegmentStart = function(dataView, offset){
return (
dataView.getUint8(offset) === 0x38 &&
dataView.getUint8(offset+1) === 0x42 &&
dataView.getUint8(offset+2) === 0x49 &&
dataView.getUint8(offset+3) === 0x4D &&
dataView.getUint8(offset+4) === 0x04 &&
dataView.getUint8(offset+5) === 0x04
);
};
while (offset < length) {
if ( isFieldSegmentStart(dataView, offset )){
// Get the length of the name header (which is padded to an even number of bytes)
var nameHeaderLength = dataView.getUint8(offset+7);
if(nameHeaderLength % 2 !== 0) nameHeaderLength += 1;
// Check for pre photoshop 6 format
if(nameHeaderLength === 0) {
// Always 4
nameHeaderLength = 4;
}
var startOffset = offset + 8 + nameHeaderLength;
var sectionLength = dataView.getUint16(offset + 6 + nameHeaderLength);
return readIPTCData(file, startOffset, sectionLength);
break;
}
// Not the marker, continue searching
offset++;
}
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
findIPTCinJPEG
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
isFieldSegmentStart = function(dataView, offset){
return (
dataView.getUint8(offset) === 0x38 &&
dataView.getUint8(offset+1) === 0x42 &&
dataView.getUint8(offset+2) === 0x49 &&
dataView.getUint8(offset+3) === 0x4D &&
dataView.getUint8(offset+4) === 0x04 &&
dataView.getUint8(offset+5) === 0x04
);
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
isFieldSegmentStart
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function readIPTCData(file, startOffset, sectionLength){
var dataView = new DataView(file);
var data = {};
var fieldValue, fieldName, dataSize, segmentType, segmentSize;
var segmentStartPos = startOffset;
while(segmentStartPos < startOffset+sectionLength) {
if(dataView.getUint8(segmentStartPos) === 0x1C && dataView.getUint8(segmentStartPos+1) === 0x02){
segmentType = dataView.getUint8(segmentStartPos+2);
if(segmentType in IptcFieldMap) {
dataSize = dataView.getInt16(segmentStartPos+3);
segmentSize = dataSize + 5;
fieldName = IptcFieldMap[segmentType];
fieldValue = getStringFromDB(dataView, segmentStartPos+5, dataSize);
// Check if we already stored a value with this name
if(data.hasOwnProperty(fieldName)) {
// Value already stored with this name, create multivalue field
if(data[fieldName] instanceof Array) {
data[fieldName].push(fieldValue);
}
else {
data[fieldName] = [data[fieldName], fieldValue];
}
}
else {
data[fieldName] = fieldValue;
}
}
}
segmentStartPos++;
}
return data;
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
readIPTCData
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function readTags(file, tiffStart, dirStart, strings, bigEnd) {
var entries = file.getUint16(dirStart, !bigEnd),
tags = {},
entryOffset, tag,
i;
for (i=0;i<entries;i++) {
entryOffset = dirStart + i*12 + 2;
tag = strings[file.getUint16(entryOffset, !bigEnd)];
if (!tag && debug) console.log("Unknown tag: " + file.getUint16(entryOffset, !bigEnd));
tags[tag] = readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd);
}
return tags;
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
readTags
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function readTagValue(file, entryOffset, tiffStart, dirStart, bigEnd) {
var type = file.getUint16(entryOffset+2, !bigEnd),
numValues = file.getUint32(entryOffset+4, !bigEnd),
valueOffset = file.getUint32(entryOffset+8, !bigEnd) + tiffStart,
offset,
vals, val, n,
numerator, denominator;
switch (type) {
case 1: // byte, 8-bit unsigned int
case 7: // undefined, 8-bit byte, value depending on field
if (numValues == 1) {
return file.getUint8(entryOffset + 8, !bigEnd);
} else {
offset = numValues > 4 ? valueOffset : (entryOffset + 8);
vals = [];
for (n=0;n<numValues;n++) {
vals[n] = file.getUint8(offset + n);
}
return vals;
}
case 2: // ascii, 8-bit byte
offset = numValues > 4 ? valueOffset : (entryOffset + 8);
return getStringFromDB(file, offset, numValues-1);
case 3: // short, 16 bit int
if (numValues == 1) {
return file.getUint16(entryOffset + 8, !bigEnd);
} else {
offset = numValues > 2 ? valueOffset : (entryOffset + 8);
vals = [];
for (n=0;n<numValues;n++) {
vals[n] = file.getUint16(offset + 2*n, !bigEnd);
}
return vals;
}
case 4: // long, 32 bit int
if (numValues == 1) {
return file.getUint32(entryOffset + 8, !bigEnd);
} else {
vals = [];
for (n=0;n<numValues;n++) {
vals[n] = file.getUint32(valueOffset + 4*n, !bigEnd);
}
return vals;
}
case 5: // rational = two long values, first is numerator, second is denominator
if (numValues == 1) {
numerator = file.getUint32(valueOffset, !bigEnd);
denominator = file.getUint32(valueOffset+4, !bigEnd);
val = new Number(numerator / denominator);
val.numerator = numerator;
val.denominator = denominator;
return val;
} else {
vals = [];
for (n=0;n<numValues;n++) {
numerator = file.getUint32(valueOffset + 8*n, !bigEnd);
denominator = file.getUint32(valueOffset+4 + 8*n, !bigEnd);
vals[n] = new Number(numerator / denominator);
vals[n].numerator = numerator;
vals[n].denominator = denominator;
}
return vals;
}
case 9: // slong, 32 bit signed int
if (numValues == 1) {
return file.getInt32(entryOffset + 8, !bigEnd);
} else {
vals = [];
for (n=0;n<numValues;n++) {
vals[n] = file.getInt32(valueOffset + 4*n, !bigEnd);
}
return vals;
}
case 10: // signed rational, two slongs, first is numerator, second is denominator
if (numValues == 1) {
return file.getInt32(valueOffset, !bigEnd) / file.getInt32(valueOffset+4, !bigEnd);
} else {
vals = [];
for (n=0;n<numValues;n++) {
vals[n] = file.getInt32(valueOffset + 8*n, !bigEnd) / file.getInt32(valueOffset+4 + 8*n, !bigEnd);
}
return vals;
}
}
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
readTagValue
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function getStringFromDB(buffer, start, length) {
var outstr = "";
for (var n = start; n < start+length; n++) {
outstr += String.fromCharCode(buffer.getUint8(n));
}
return outstr;
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
getStringFromDB
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function readEXIFData(file, start) {
if (getStringFromDB(file, start, 4) != "Exif") {
if (debug) console.log("Not valid EXIF data! " + getStringFromDB(file, start, 4));
return false;
}
var bigEnd,
tags, tag,
exifData, gpsData,
tiffOffset = start + 6;
// test for TIFF validity and endianness
if (file.getUint16(tiffOffset) == 0x4949) {
bigEnd = false;
} else if (file.getUint16(tiffOffset) == 0x4D4D) {
bigEnd = true;
} else {
if (debug) console.log("Not valid TIFF data! (no 0x4949 or 0x4D4D)");
return false;
}
if (file.getUint16(tiffOffset+2, !bigEnd) != 0x002A) {
if (debug) console.log("Not valid TIFF data! (no 0x002A)");
return false;
}
var firstIFDOffset = file.getUint32(tiffOffset+4, !bigEnd);
if (firstIFDOffset < 0x00000008) {
if (debug) console.log("Not valid TIFF data! (First offset less than 8)", file.getUint32(tiffOffset+4, !bigEnd));
return false;
}
tags = readTags(file, tiffOffset, tiffOffset + firstIFDOffset, TiffTags, bigEnd);
if (tags.ExifIFDPointer) {
exifData = readTags(file, tiffOffset, tiffOffset + tags.ExifIFDPointer, ExifTags, bigEnd);
for (tag in exifData) {
switch (tag) {
case "LightSource" :
case "Flash" :
case "MeteringMode" :
case "ExposureProgram" :
case "SensingMethod" :
case "SceneCaptureType" :
case "SceneType" :
case "CustomRendered" :
case "WhiteBalance" :
case "GainControl" :
case "Contrast" :
case "Saturation" :
case "Sharpness" :
case "SubjectDistanceRange" :
case "FileSource" :
exifData[tag] = StringValues[tag][exifData[tag]];
break;
case "ExifVersion" :
case "FlashpixVersion" :
exifData[tag] = String.fromCharCode(exifData[tag][0], exifData[tag][1], exifData[tag][2], exifData[tag][3]);
break;
case "ComponentsConfiguration" :
exifData[tag] =
StringValues.Components[exifData[tag][0]] +
StringValues.Components[exifData[tag][1]] +
StringValues.Components[exifData[tag][2]] +
StringValues.Components[exifData[tag][3]];
break;
}
tags[tag] = exifData[tag];
}
}
if (tags.GPSInfoIFDPointer) {
gpsData = readTags(file, tiffOffset, tiffOffset + tags.GPSInfoIFDPointer, GPSTags, bigEnd);
for (tag in gpsData) {
switch (tag) {
case "GPSVersionID" :
gpsData[tag] = gpsData[tag][0] +
"." + gpsData[tag][1] +
"." + gpsData[tag][2] +
"." + gpsData[tag][3];
break;
}
tags[tag] = gpsData[tag];
}
}
return tags;
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
readEXIFData
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
getElementOffset=function(elem) {
var box = elem.getBoundingClientRect();
var body = document.body;
var docElem = document.documentElement;
var scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop;
var scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft;
var clientTop = docElem.clientTop || body.clientTop || 0;
var clientLeft = docElem.clientLeft || body.clientLeft || 0;
var top = box.top + scrollTop - clientTop;
var left = box.left + scrollLeft - clientLeft;
return { top: Math.round(top), left: Math.round(left) };
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
getElementOffset
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
function drawScene() {
// clear canvas
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
if(image!==null) {
// draw source image
ctx.drawImage(image, 0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.save();
// and make it darker
ctx.fillStyle = 'rgba(0, 0, 0, 0.65)';
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
ctx.restore();
// draw Area
theArea.draw();
}
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
drawScene
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
resetCropHost=function() {
if(image!==null) {
theArea.setImage(image);
var imageDims=[image.width, image.height],
imageRatio=image.width/image.height,
canvasDims=imageDims;
if(canvasDims[0]>maxCanvasDims[0]) {
canvasDims[0]=maxCanvasDims[0];
canvasDims[1]=canvasDims[0]/imageRatio;
} else if(canvasDims[0]<minCanvasDims[0]) {
canvasDims[0]=minCanvasDims[0];
canvasDims[1]=canvasDims[0]/imageRatio;
}
if(canvasDims[1]>maxCanvasDims[1]) {
canvasDims[1]=maxCanvasDims[1];
canvasDims[0]=canvasDims[1]*imageRatio;
} else if(canvasDims[1]<minCanvasDims[1]) {
canvasDims[1]=minCanvasDims[1];
canvasDims[0]=canvasDims[1]*imageRatio;
}
elCanvas.prop('width',canvasDims[0]).prop('height',canvasDims[1]).css({'margin-left': -canvasDims[0]/2+'px', 'margin-top': -canvasDims[1]/2+'px'});
theArea.setX(ctx.canvas.width/2);
theArea.setY(ctx.canvas.height/2);
theArea.setSize(Math.min(200, ctx.canvas.width/2, ctx.canvas.height/2));
} else {
elCanvas.prop('width',0).prop('height',0).css({'margin-top': 0});
}
drawScene();
}
|
EXIF service is based on the exif-js library (https://github.com/jseidelin/exif-js)
|
resetCropHost
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
getChangedTouches=function(event){
if(angular.isDefined(event.changedTouches)){
return event.changedTouches;
}else{
return event.originalEvent.changedTouches;
}
}
|
Returns event.changedTouches directly if event is a TouchEvent.
If event is a jQuery event, return changedTouches of event.originalEvent
|
getChangedTouches
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
onMouseMove=function(e) {
if(image!==null) {
var offset=getElementOffset(ctx.canvas),
pageX, pageY;
if(e.type === 'touchmove') {
pageX=getChangedTouches(e)[0].pageX;
pageY=getChangedTouches(e)[0].pageY;
} else {
pageX=e.pageX;
pageY=e.pageY;
}
theArea.processMouseMove(pageX-offset.left, pageY-offset.top);
drawScene();
}
}
|
Returns event.changedTouches directly if event is a TouchEvent.
If event is a jQuery event, return changedTouches of event.originalEvent
|
onMouseMove
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
onMouseDown=function(e) {
e.preventDefault();
e.stopPropagation();
if(image!==null) {
var offset=getElementOffset(ctx.canvas),
pageX, pageY;
if(e.type === 'touchstart') {
pageX=getChangedTouches(e)[0].pageX;
pageY=getChangedTouches(e)[0].pageY;
} else {
pageX=e.pageX;
pageY=e.pageY;
}
theArea.processMouseDown(pageX-offset.left, pageY-offset.top);
drawScene();
}
}
|
Returns event.changedTouches directly if event is a TouchEvent.
If event is a jQuery event, return changedTouches of event.originalEvent
|
onMouseDown
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
onMouseUp=function(e) {
if(image!==null) {
var offset=getElementOffset(ctx.canvas),
pageX, pageY;
if(e.type === 'touchend') {
pageX=getChangedTouches(e)[0].pageX;
pageY=getChangedTouches(e)[0].pageY;
} else {
pageX=e.pageX;
pageY=e.pageY;
}
theArea.processMouseUp(pageX-offset.left, pageY-offset.top);
drawScene();
}
}
|
Returns event.changedTouches directly if event is a TouchEvent.
If event is a jQuery event, return changedTouches of event.originalEvent
|
onMouseUp
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
updateResultImage=function(scope) {
var resultImage=cropHost.getResultImageDataURI();
if(storedResultImage!==resultImage) {
storedResultImage=resultImage;
if(angular.isDefined(scope.resultImage)) {
scope.resultImage=resultImage;
}
scope.onChange({$dataURI: scope.resultImage});
}
}
|
Returns event.changedTouches directly if event is a TouchEvent.
If event is a jQuery event, return changedTouches of event.originalEvent
|
updateResultImage
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.js
|
MIT
|
fnSafeApply=function(fn) {
return function(){
$timeout(function(){
scope.$apply(function(scope){
fn(scope);
});
});
};
}
|
Returns event.changedTouches directly if event is a TouchEvent.
If event is a jQuery event, return changedTouches of event.originalEvent
|
fnSafeApply
|
javascript
|
danialfarid/ng-file-upload
|
demo/src/main/webapp/js/ng-img-crop.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/demo/src/main/webapp/js/ng-img-crop.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
|
dist/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/FileAPI.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload-all.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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
|
dist/ng-file-upload.js
|
https://github.com/danialfarid/ng-file-upload/blob/master/dist/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.