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

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

Related

downloading text file in postman but not in browser using restapi in angularjs

$scope.newFile is my response from backend. Actually my response should be a text file, which is working in postman.But in browser , I am getting
Cannot GET
/Organizer/%7B%22data%22:%22id/tname/temail/tphone/twebsite/tvenue/ttags/n83/tAny%20Name/ta#b.com/t9009009009/thttp://www.anyname.com/tHall%20A/ttag1,%20tag2,%20tag3/nsunitha/tsunitha#gmail.com/t55555541/thttp://www.sunitha.com/nSuhasini/tsuha#gmail.com/t955555544/thttp://www.suha.com/nRaichel/traichel#gmail.com/t955548458/thttp://www.raichel.com/n%22,%22status%22:200,%22config%22:%7B%22method%22:%22GET%22,%22transformRequest%22:[null],%22transformResponse%22:[null],%22jsonpCallbackParam%22:%22callback%22,%22headers%22:%7B%22Authorization%22:%22Token%2013946cc6c575d61b042b01b6905f1d239b3d9b08%22,%22Accept%22:%22application/json,%20text/plain,%20*/*%22%7D,%22url%22:%22http://http://localhost/1290//entity/campaigns/download_exhibitors/%22%7D,%22statusText%22:%22OK%22,%22xhrStatus%22:%22complete%22%7D
Service.js
var url =' http://localhost/1290/';
function downloadExhibitor() {
var token = 129821sahh;
var auth = "Token" + ' ' + token;
var config = {
headers: {
'Content-Type': 'text/plain',
'Authorization': auth
}
}
return $http.get(url + 'entity/campaigns/download_exhibitors/', config)
.then(successHandler, errorHandler);
}
function successHandler(response){
/* we've got file's data from server */
return response.data;
}
function errorHandler(error){
/* we've got error response from server */
throw new Error('ERROR ' + error);
}
and eventually the service invocation
JS:
$scope.newFile = "";
service.downloadExhibitor()
.then(function(data){
$scope.newFile = data;
}, function(error){
console.log(error);
});
HTML:
<button class="btn" ng-click="downloadAllExhibitors();">
<a ng-href="{{newFile}}" target="_blank">Download</a></button>
You can try below code in controller...
var file = new Blob([data], {
type : 'text/plain'
});
if (navigator.userAgent.indexOf('MSIE') !== -1
|| navigator.appVersion.indexOf('Trident/') > 0) {
window.navigator.msSaveOrOpenBlob(file);
} else {
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
}
Following code in controller made my work simple , and it downloaded the file finally.
var file = new Blob([data], {
type: 'text/plain'
});
if (navigator.userAgent.indexOf('MSIE') !== -1 ||
navigator.appVersion.indexOf('Trident/') > 0) {
window.navigator.msSaveOrOpenBlob(file);
} else {
var a = window.document.createElement("a");
a.href = window.URL.createObjectURL(file, {
type: "text/plain"
});
a.download = "filename.csv";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}

Angularjs timeout

why is this time out not working? I have injected $timeout in controller. Even moving timeout into http response is the same. Using angularjs 1.6.6 with Laravel 5.2. $scope.showInfo is true, but not false after 3000 ms.
$scope.submitAttendance = function(attData) {
$http({
method: 'POST',
url: '/api/save/attendance',
headers: { 'Content-Type' : 'application/json' },
data: attData
}).then(function successCallback(response) {
var response = response.data;
if (response == 1) {
$scope.msg = 'Attendance details saved to system';
$scope.attData = {};
$scope.attData.timeIn = new Date (new Date().toDateString() + ' ' + '08:00');
$scope.attData.timeOut = new Date (new Date().toDateString() + ' ' + '16:00');
} else {
$scope.msg = 'Failed to save Attendance info';
}
}, function errorCallback(response) {
$scope.msg = 'There is a problem saving data at this time. Please contact Administrator';
});
$scope.showInfo = true;
$timeout(function(){ $scope.showinfo = false; }, 3000);
}

Download Base64 in AngularJS

Hi guys I am trying to download a Base64 file but I get (we can't open this file) see the image and my code below
_thisSearchView.$scope.downloadViewAttachment = function (firstId) {
var idValue = couchObjectId.substr(4, couchObjectId.indexOf('_rev=') - 4);
$http.defaults.headers.common['Authorization'] = "Basic " + _thisSearchView.$scope.config.params.COUCHDB_SERVER_KEY;
$http({
method: "GET",
url: _thisSearchView.$scope.config.params.COUCHDB_SERVER_URL + idValue + '/' + attachName,
}).then(function mySuccess(response) {
try {
var blob = new Blob([response.data], {
type: "text/plain;charset=utf-8"
});
saveAs(blob, attachName);
}
catch (ex) {
console.log(ex);
}
}, function myError(response) {
if (response.status === 404) {
_thisSearchView.$scope.downloadViewArchDcoument();
}
});
};

$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 can I post data as form data with Angular

I want to send an avatar to my server but I have this error "You must include 'avatar' file var in your POST form data."
function getPictureSuccess(imageData) {
var image = "data:image/jpeg;base64," + imageData;
$scope.avatar = image;
}
$http({
url: api_url + 'userplus/avatar_upload/?key=' + api_key + '&cookie=' + dataCookie,
method:"POST",
headers : {'Content-Type': 'application/x-www-form-urlencoded'},
data: {avatar: avatar}
});
Change data: {avatar: avatar} to data: {avatar: $scope.avatar}
try
imgURI = "data:image/jpeg;base64," + imageData;
var FD = new FormData();
FD.append('image', dataURItoBlob(imgURI), 'image.jpg'); // "image" This is what you get at server side so change it accord inly
FD.append("Other Param", 'other Param value ') // other parameter needed to post
$http.post('Your Url', DataObj, {
headers: {
'Content-Type': undefined
},
transformRequest: angular.identity
}).then(function(responce) {
responce.data;
})
// And here is your helper function
function dataURItoBlob(dataURI) {
// convert base64/URLEncoded data component to raw binary data held in a string
var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
var bb = new Blob([ab], {
"type": mimeString
});
return bb;
}

Resources