Currently facing a challenge with the code snippet below:
app.factory('sfAttachment', ['$http', '$q', '$window', '$rootScope', function($http, $q, $window, $rootScope) {
var attachment = {};
//Function to save attachments to the server
attachment.save = function(base64value, document, index) {
//Removing unnecessary file type text from the base64 value
var position = base64value.indexOf("base64,");
var matchWord = "base64,";
var base64valueClean = base64value.slice(position + matchWord.length, base64value.length);
//Data payload for saving in SF database
var data = {
"Body": base64valueClean,
"ContentType": document.attachmentContentType,
"ParentId": document.id,
"Name": document.fileName
};
//Getting the URL value for posting to SF database
var url = $window.__url;
var method = 'POST';
var request = {
url: url,
method: method,
data: data,
headers: {
__XHR__: function() {
return function(xhr) {
xhr.upload.addEventListener("progress", function(event) {
$rootScope.text = event.loaded/event.total;
$rootScope.$apply();
console.log("uploaded " + ((event.loaded/event.total) * 100) + "%");
});
};
}
}
};
console.log(request);
//Using promise approach for HTTP request
var deferred = $q.defer();
//Making HTTP request to the server
$http(request).then(function(response) {
deferred.resolve(response);
console.log('File UPLOADED to SF!');
}, function(event) {
//Improvements needed in error handling
deferred.reject('The attachment could not be saved:' + event);
});
return deferred.promise;
}
This service successfully loads an Attachment into Salesforce. I added code
headers: {
__XHR__: function() {
return function(xhr) {
xhr.upload.addEventListener("progress", function(event) {
$rootScope.text = event.loaded / event.total;
$rootScope.$apply();
console.log("uploaded " + ((event.loaded / event.total) * 100) + "%");
});
};
to monitor upload progress and it displays the percentage in the console. Now, I want to pass this progress percentage to the controller that calls this service. I'm having trouble figuring out how to grab the text properly, currently using $rootScope.text
and setting up a watch in my controller. It works, but is there a better way to achieve this?
$rootScope.$watch('text', function(newValue, oldValue, scope) {
console.log($rootScope.text);
});