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
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;
});
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;
});
});
});
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.
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