Jquery file upload autoupload and frontend validation before upload - angularjs

I use plugin from: https://github.com/blueimp/jQuery-File-Upload
My script loading order is:
jquery.js, angular.js, jquery.ui.widget.js, jquery.iframe-transport.js, jquery.fileupload.js, jquery.fileupload-process.js, jquery.fileupload-validate.js, jquery.fileupload-angular.js
My controller is:
$scope.profileUploadOptions = {
url: API_URL + "images/user",
maxFileSize: 50,
acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i,
forceIframeTransport: false,
add: function(e, data) {
$.each(data.files, function (index, file) {
console.log("Added file: " + file.name);
});
console.log(data);
},
start: function(e) {
console.log("Uploads started");
},
stop: function (e) {
console.log("Uploads finished");
},
change: function (e, data) {
$.each(data.files, function (index, file) {
console.log("Changed file: " + file.name);
});
},
progress: function(e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
console.log("Progress: " + progress);
},
progressAll: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
console.log("Progress: " + progress);
},
done: function(e, data) {
console.log("Done: ");
console.log(data);
},
fail: function(e, data) {
console.log("Fail: ");
console.log(data);
},
always: function(e, data) {
console.log("Always: ");
console.log(data);
}
};
How i can submit upload after browse single file from browse window, and where i can handle errors if file type not in acceptFileTypes Regex, or is bigger than maxFileSize?

The plugin documentation should answer your question on auto-uploading, and there are a host of examples that are easy enough to find regarding setting up the fileinput piece of your question.
As far as validating files before submitting an upload, this posed answer, pasted below, is a good starting point.
$fileInput.fileupload({
url: 'upload_url',
type: 'POST',
dataType: 'json',
autoUpload: false,
disableValidation: false,
maxFileSize: 1024 * 1024,
messages: {
maxFileSize: 'File exceeds maximum allowed size of 1MB',
}
});
$fileInput.on('fileuploadadd', function(evt, data) {
var $this = $(this);
var validation = data.process(function () {
return $this.fileupload('process', data);
});
validation.done(function() {
makeAjaxCall('some_other_url', { fileName: data.files[0].name, fileSizeInBytes: data.files[0].size })
.done(function(resp) {
data.formData = data.formData || {};
data.formData.someData = resp.SomeData;
data.submit();
});
});
validation.fail(function(data) {
console.log('Upload error: ' + data.files[0].error);
});
});
Using the other author's code, the providing user feedback can be achieved in the validation.fail handler.

Related

$cordovaFileTransfer can not work

use $cordovaFileTransfer to upload images,but it stop at 99%, $_FILES is empty in PHP;
and i get evt object.
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"16656","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"33040","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"98576","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"131344","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"147728","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"164112","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"180496","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"213264","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"229648","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"65808","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"82192","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"114960","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"295184","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"262416","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"311568","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"327952","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"344336","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"360720","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"377104","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"409872","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"442640","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"393488","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"426256","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"459024","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"475408","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"491163","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"196880","total":"491176"}
{"bubbles":"false","cancelBubble":"false","cancelable":"false","lengthComputable":"true","loaded":"246032","total":"491176"}
what's wrong with the property loaded;why it increase repeatly;
upload code
$scope.upload = function(imageURI) {
$scope.dangerList[$scope.setting.num][$scope.setting.imageType + '1pic'] = imageURI;
var server = 'http://localhost/test.php';
var dirName = 'check';
var desName = 'test';
var options = {
'httpMethod': 'POST',
'params': {
'dirName': dirName,
'desName': desName
}
};
var promise = $cordovaFileTransfer.upload(server, imageURI, options, true);
promise.then(function(data) {
console.log(data);
}, function(data) {}, function(evt) {
$ionicLoading.show({
template: '<p>upload:' + parseInt(100.0 * evt.loaded / evt.total) + '%</p>',
//duration: 1000,
});
});
return promise;
};
and ngCordova\src\plugins\fileTransfer.js
angular.module('ngCordova.plugins.fileTransfer', [])
.factory('$cordovaFileTransfer', ['$q', '$timeout', function($q, $timeout) {
return {
download: function(source, filePath, options, trustAllHosts) {
var q = $q.defer();
var ft = new FileTransfer();
var uri = (options && options.encodeURI === false) ? source : encodeURI(source);
if (options && options.timeout !== undefined && options.timeout !== null) {
$timeout(function() {
ft.abort();
}, options.timeout);
options.timeout = null;
}
ft.onprogress = function(progress) {
q.notify(progress);
};
q.promise.abort = function() {
ft.abort();
};
ft.download(uri, filePath, q.resolve, q.reject, trustAllHosts, options);
return q.promise;
},
upload: function(server, filePath, options, trustAllHosts) {
var q = $q.defer();
var ft = new FileTransfer();
var uri = (options && options.encodeURI === false) ? server : encodeURI(server);
if (options && options.timeout !== undefined && options.timeout !== null) {
$timeout(function() {
ft.abort();
}, options.timeout);
options.timeout = null;
}
ft.onprogress = function(progress) {
q.notify(progress);
};
q.promise.abort = function() {
ft.abort();
};
ft.upload(filePath, uri, q.resolve, q.reject, options, trustAllHosts);
return q.promise;
}
};
}]);
and push interceptor
.factory('UserInterceptor', function ($q, $rootScope) {
return {
request:function(config){
config.headers = config.headers || {};
config.headers.UID = $rootScope.user.id || 0;
return config;
},
requestError: function(err){
return $q.reject(err);
},
response: function (response) {
return response;
},
};
})
it could work few days ago.
during the time,
add plaform with android#5.1.1 instead of android#4.1.1;
update cordova;
use ionic 1.7.3 now;
and here is the download code,it can works,but will download file twice
$scope.down = function(fname) {
var fileTransfer = new FileTransfer();
var uri = encodeURI($rootScope.rootUrl + fname);
var fileURL = cordova.file.externalRootDirectory + fname;
fileTransfer.download(
uri,
fileURL,
function(entry) {
console.log(entry);
},
function(error) {
console.log(error);
},
false, {
headers: {
"Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
);
};
This is actually the response from progress event of cordovaFileTransfer.
On success it'll give response something like this:
Object {bytesSent: 3228135, responseCode: 200, response: "<!-- Served from 80.251.0.59 / test.talia.net, as …imited↵</p>↵↵</td></tr></table>↵↵</body>↵</html>↵", objectId: ""}
But as per the output you are getting,I think the function is getting interrupted by the same method from another instance because your whole file was almost uploaded in the 3rd last line.
"cancelable":"false","lengthComputable":"true","loaded":"491163","total":"491176"}
And then it picked up from some another point.
Please provide the code so I can try to assist you further.
Thank you

How to delete file in dropzone?

init: function() {
dzClosure = this;
document.getElementById("place-order").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("key", $scope.formData.order_id);
});
this.on('success', function(file, resp) {
console.log(resp); //result - {error:false, file_id:10}
file_ids.push(resp.file_id);
});
},
removedfile: function(file) {
console.log(file_ids);
x = confirm('Do you want to delete?');
if (!x) return false;
var name = file.name;
$.ajax({
type: 'POST',
url: 'orders/fileDelete.php',
data: {"file_id": file_ids},
dataType: 'json'
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
Above my code working fine. But I want to delete my mysql row while clicking on the "Remove" button in dropzone. I am unable to get the current file_id in my removedfile function. Please help me and let me know how I will get resp.file_id in my removedfile function?
You could set an id property to file on success event, then on removal just get it as file.id. Hope this helps you.
init: function() {
dzClosure = this;
document.getElementById("place-order").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
dzClosure.processQueue();
});
this.on("sendingmultiple", function(data, xhr, formData) {
formData.append("key", $scope.formData.order_id);
});
this.on('success', function(file, resp) {
file.id = resp.file_id;
});
},
removedfile: function(file) {
x = confirm('Do you want to delete?');
if (!x) return false;
//send delete to backend only if file was uploaded.
//Dropzone will cancel requests in progress itself.
if(file.id) {
$.ajax({
type: 'POST',
url: 'orders/fileDelete.php',
data: {"file_id": file.id},
dataType: 'json'
});
}
}
After lots of research I found where was error in my code.
Actually my ajax responded JSON. But here is dropzone.js not getting json data. So I have converted my dynamic String data to JSON format.
Code:
this.on('success', function(file, resp) {
console.log(resp); // result - {error:false, file_id:10}
var response = JSON.parse(resp);
file.file_id = response.file_id;
});

Angular resolve promise and update existing scope

I am trying to understand Angular's promises and scopes. Actually I implemented the directive bellow. The thing that I want to do is to receive images from server and store locally in order to cache them for next times. Also I want to show a spinner before the load of image is completed and show it after the completion.
How can update variable newUrl into directive when completed all of these promises?
Do you have any idea?
My HTML code is:
<div style="text-align: center;"
cache-src
url="https://upload.wikimedia.org/wikipedia/commons/c/c0/Aix_galericulata_(Male),_Richmond_Park,_UK_-_May_2013.jpg">
</div>
My directive is:
.directive('cacheSrc', [function () {
return {
restrict: 'A',
scope: {
url: '#'
},
controller: 'cacheSrcCtrl',
template: '<img width="100%" ng-if="newUrl!=null" src="{{newUrl}}"><ion-spinner ng-if="newUrl==null" icon="spiral"></ion-spinner>',
};
}])
And the controller of directive has the function bellow:
document.addEventListener('deviceready', function () {
$scope.updateUrl = function (newUrl) {
$scope.newUrl = newUrl;
};
var tmp = $scope.url;
$cordovaSQLite.execute(db, 'SELECT * FROM images where url = (?)', [tmp])
.then(function (result) {
if (result.rows.length > 0) {
$scope.exists = true;
for (var i = 0; i < res.rows.length; i++) {
var image = {
id: res.rows.item(i).id,
url: res.rows.item(i).url,
uri: res.rows.item(i).uri
};
$scope.updateUrl(image.uri);
}
} else {
$scope.exists = false;
var fileTransfer = new FileTransfer();
var uri = encodeURI(tmp);
var uriSave = '';
var fileURL = cordova.file.dataDirectory + uri;//'kaloudiaImages';// + getUUID();// + "DCIM/myFile";
fileTransfer.download(
uri, fileURL, function (entry) {
uriSave = entry.toURL();
KaloudiaDB.add(tmp, fileURL);
$scope.newUrl = fileURL;
$scope.updateUrl(fileURL);
},
function (error) {
console.log("download error code" + error.code);
},
false, {
headers: {
// "Authorization": "Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=="
}
}
).then(function (data) {
$scope.newUrl = fileURL;
});
}
}, function (error) {
$scope.statusMessage = "Error on saving: " + error.message;
})
.then(function (data) {
$scope.$apply(function () {
$scope.newUrl = fileURL;
});
});
});

Upload image to server with ionic/angularjs

I want upload image to server with ionic.
I use this factory:
(function () {
function ius($q, $ionicLoading, $cordovaFile ) {
var service = {};
service.uploadImage = uploadImage;
return service;
function uploadImage(imageURI) {
var deferred = $q.defer();
var fileSize;
var percentage;
// Find out how big the original file is
window.resolveLocalFileSystemURL(imageURI, function (fileEntry) {
fileEntry.file(function (fileObj) {
fileSize = fileObj.size;
// Display a loading indicator reporting the start of the upload
$ionicLoading.show({ template: 'Uploading Picture : ' + 0 + '%' });
// Trigger the upload
uploadFile();
});
});
function uploadFile() {
// Add the Cloudinary "upload preset" name to the headers
var uploadOptions = {
params: { 'upload_preset': CLOUDINARY_CONFIGS.UPLOAD_PRESET } //CLOUDINARY_CONFIGS.UPLOAD_PRESET
};
$cordovaFile
// Your Cloudinary URL will go here
.uploadFile(CLOUDINARY_CONFIGS.API_URL, imageURI, uploadOptions) //
.then(function (result) {
// Let the user know the upload is completed
$ionicLoading.show({ template: 'Upload Completed', duration: 1000 });
// Result has a "response" property that is escaped
// FYI: The result will also have URLs for any new images generated with
// eager transformations
var response = JSON.parse(decodeURIComponent(result.response));
deferred.resolve(response);
}, function (err) {
// Uh oh!
$ionicLoading.show({ template: 'Upload Failed', duration: 3000 });
deferred.reject(err);
}, function (progress) {
// The upload plugin gives you information about how much data has been transferred
// on some interval. Use this with the original file size to show a progress indicator.
percentage = Math.floor(progress.loaded / fileSize * 100);
$ionicLoading.show({ template: 'Uploading Picture : ' + percentage + '%' });
});
}
return deferred.promise;
}
}
angular.module('App').factory('ImageUploadService', ius);
})();
And i call this function :
'Use Strict';
angular.module('App').controller('editeventController', function ($scope,ImageUploadService) {
$scope.upload = function () {
ImageUploadService.uploadImage("img/test.jpg").then(
function (result) {
var url = result.secure_url || '';
var urlSmall;
if (result && result.eager[0]) urlSmall = result.eager[0].secure_url || '';
// Do something with the results here.
$cordovaCamera.cleanup();
},
function (err) {
// Do something with the error here
$cordovaCamera.cleanup();
});
}
But, when I try to upload, I have this error:
TypeError: window.resolveLocalFileSystemURL is not a function
at Object.uploadImage (http://localhost:8100/js/services/utils.js:177:20)
at Scope.$scope.upload (http://localhost:8100/views/editevent/editevent.js:199:28)
at fn (eval at (http://localhost:8100/lib/ionic/js/ionic.bundle.js:26457:15),
:4:209)
at http://localhost:8100/lib/ionic/js/ionic.bundle.js:62386:9
at Scope.$eval (http://localhost:8100/lib/ionic/js/ionic.bundle.js:29158:28)
at Scope.$apply (http://localhost:8100/lib/ionic/js/ionic.bundle.js:29257:23)
at HTMLButtonElement. (http://localhost:8100/lib/ionic/js/ionic.bundle.js:62385:13)
at HTMLButtonElement.eventHandler (http://localhost:8100/lib/ionic/js/ionic.bundle.js:16583:21)
at triggerMouseEvent (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2948:7)
at tapClick (http://localhost:8100/lib/ionic/js/ionic.bundle.js:2937:3)
[edit]
I use requestFileSystem instead of resolveLocalFileSystemURL
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 0, onSuccess, onError);
function onSuccess(fileSystem) {
var directoryEntry = fileSystem.root;
console.log(directoryEntry);
directoryEntry.getFile(imageURI, { create: true, exclusive: false }, function (fileEntry) {
console.log(fileEntry);
fileEntry.createWriter(function (writer) {
// writer.write("This is the text inside readme file");
var pathOfFile = fileEntry.fullPath;
console.log(pathOfFile);
fileSize = fileEntry.size;
// Display a loading indicator reporting the start of the upload
$ionicLoading.show({ template: 'Uploading Picture : ' + 0 + '%' });
uploadFile();
}, function (error) {
alert("Error occurred while writing to file. Error is: " + error.message);
});
}, function (error) {
console.log(error.message);
alert("Error occurred while getting a pointer to file. Error is: " + error.message);
});
}
function onError(evt) {
alert("Error occurred during request to file system pointer. Error is: " + evt.message);
}
Now I have this error:
The operation failed because it would cause the application to exceed
its storage quota.

IE10 - Page Blank when window.open(trustedURL) - PDF ANGULAR JS

I tried to generate a PDF since data returned from API.
All working find exept for IE 10, Edge which open a blank window ! I dont know what happening...
Controller function :
(fileRequest = User.getFile($rootScope.PARAMS, 'facture', 'arraybuffer')).then(function(dataFactureFile)
{
var file = new Blob([dataFactureFile], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.content = $sce.trustAsResourceUrl(fileURL);
$timeout(function()
{
if(action == 'view')
{
$window.open($scope.content);
}
if(action == 'download')
{
var anchor = document.createElement("a");
anchor.setAttribute('download', false);
anchor.download = 'FACTURE-' + $scope.infosFacture.type + '-' + $scope.infosFacture.date + '.pdf';
anchor.href = $scope.content;
anchor.click();
}
}, 500);
}, function(reason){
if(reason != 'aborted')
{
// REJECT
$scope.popin(reason.errorCode, reason.errorMsg);
}
});
Service :
getFile: function(user, type, type_response)
{
var deferredAbort = $q.defer();
var request = $http({
method: "post",
url: $rootScope.directory + 'api/' + type,
data: user,
headers: {
'Content-Type': 'api/downloadPDF'
},
responseType : type_response,
timeout: deferredAbort.promise
}).then(
function(response) {
return(response.data);
},
function(response) {
return($q.reject('aborted'));
}
);
request.abort = function() {
deferredAbort.resolve();
};
return(request);
},
In addition, the "anchor.click()" seems to not working with IE :/, somebody have a tip for simulate download click ?
Thank's you

Resources