Angularjs PDF download in mobile device is not working? - angularjs

This is my download URL:
http://xxx.xxx.xxx.xxx/gk/panel/user/index/export/type/pdf/qid/238/formData/{"users":{"firstname":"dhamskar"}}
This is my controller:
$scope.downloadPDF = function() {
// Use an arraybuffer
$http.get('http://xxx.xxx.xxx.xxx/gk/panel/user/index/export/type/pdf/qid/238/formData/{"users":{"firstname":"dhamskar"}}', { responseType: 'arraybuffer' })
.success( function(data, status, headers) {
var octetStreamMime = 'application/pdf';
var success = false;
// Get the headers
headers = headers();
// Get the filename from the x-filename header or default to "download.bin"
var filename = headers['Content-Disposition'] || group_name+'_export_user_management.pdf';
// Determine the content type from the header or default to "application/octet-stream"
var contentType = headers['content-type'] || octetStreamMime;
try
{
// Try using msSaveBlob if supported
console.log("Trying saveBlob method ...");
var blob = new Blob([data], { type: contentType });
if(navigator.msSaveBlob)
navigator.msSaveBlob(blob, filename);
else {
// Try using other saveBlob implementations, if available
var saveBlob = navigator.webkitSaveBlob || navigator.mozSaveBlob || navigator.saveBlob;
if(saveBlob === undefined) throw "Not supported";
saveBlob(blob, filename);
}
console.log("saveBlob succeeded");
success = true;
} catch(ex)
{
console.log("saveBlob method failed with the following exception:");
console.log(ex);
}
if(!success)
{
// Get the blob url creator
var urlCreator = window.URL || window.webkitURL || window.mozURL || window.msURL;
if(urlCreator)
{
// Try to use a download link
var link = document.createElement('a');
if('download' in link)
{
// Try to simulate a click
try
{
// Prepare a blob URL
console.log("Trying download link method with simulated click ...");
var blob = new Blob([data], { type: contentType });
var url = urlCreator.createObjectURL(blob);
var url1 = $sce.trustAsResourceUrl(url);
console.log("print url:"+url1);
link.setAttribute('href', url1);
// Set the download attribute (Supported in Chrome 14+ / Firefox 20+)
link.setAttribute("download", filename);
// Simulate clicking the download link
var event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
link.dispatchEvent(event);
console.log("Download link method with simulated click succeeded");
success = true;
} catch(ex) {
console.log("Download link method with simulated click failed with the following exception:");
console.log(ex);
}
}
if(!success)
{
// Fallback to window.location method
try
{
// Prepare a blob URL
// Use application/octet-stream when using window.location to force download
console.log("Trying download link method with window.location ...");
var blob = new Blob([data], { type: octetStreamMime });
var url = urlCreator.createObjectURL(blob);
var url1 = $sce.trustAsResourceUrl(url);
console.log("print url:"+url1);
window.location = url1;
console.log("Download link method with window.location succeeded");
success = true;
} catch(ex) {
console.log("Download link method with window.location failed with the following exception:");
console.log(ex);
}
}
}
}
if(!success)
{
// Fallback to window.open method
console.log("No methods worked for saving the arraybuffer, using last resort window.open");
window.open(url1, '_blank', '');
}
})
.error(function(data, status) {
console.log("Request failed with status: " + status);
// Optionally write the error out to scope
$scope.errorDetails = "Request failed with status: " + status;
});
};

Use the following to troubleshoot:
A relative path rather than an absolute path
navigator.registerContentHandler
pdf.js or downloadify as a service

Related

Donwload file in AngularJS from API REST generate file corrupted

I've generated a excel report on the API REST and send it to the front (AngularJS). If I hit the url directly from the browser everything is working fine, but no if I do it from Angularjs, the is dowloaded but when I try to open it say :
Excel cannot open the file 'filename.xlsx' because the file format or
file extension is not valid. Verify that the file has not been
corrupted and that the file extension matches the format of the file."
This is my code :
$http.get(urls.SERVICE_API + "informe/"+ angular.toJson(informeDTO)).then(
function(response) {
console.log(response.data);
console.log(response.headers('Content-Type'));
console.log(response.config);
var headers = response.headers;
var filename = "IOPReport.xlsx";
var contentType = response.headers('Content-Type');
var linkElement = document.createElement('a');
try {
var blob = new Blob([response.data], { type: contentType });
var url = window.URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
linkElement.setAttribute("download", filename);
var clickEvent = new MouseEvent("click", {
"view": window,
"bubbles": true,
"cancelable": false
});
linkElement.dispatchEvent(clickEvent);
} catch (ex) {
console.log(ex);
}
console.log("GenerarInformeIOP - success");
deferred.resolve(response);
}, function(errResponse) {
console.log("GenerarInformeIOP - error");
deferred.reject(errResponse);
});
return deferred.promise;
}
} ]);
Any idea why is not working?
Maybe you also need to adding BOM if it is CSV:
// HTTP response data
var data = response.data;
if (type === 'csv') {//Adding BOM at start of content if it is a csv
data = '\uFEFF' + data;
}
You need to append the linkElement to body before clicking:
var url = URL.createObjectURL(blob);
linkElement.setAttribute('href', url);
linkElement.setAttribute('download', filename);
linkElement.style.visibility = 'hidden';
document.body.appendChild(link);
linkElement.click();
document.body.removeChild(link);
H I resolved it adding the response type to the GET
var config = { responseType: 'blob' };
$http.get(urls.SERVICE_API + "informe/"+ angular.toJson(informeDTO), config).then(
.....
]);

Angularjs Form data is not binding at server side during file uploade

When im tring to uploade my file into server im getting an Error as TypeError: $http(...).success is not a function(…)
Angular File change code
$scope.ChechFileValid = function (file) {
debugger;
var isValid = false;
if ($scope.SelectedFileForUpload != null) {
if ((file.type == 'image/png' || file.type == 'image/jpeg' || file.type == 'image/gif') && file.size <= (512 * 1024)) {
$scope.FileInvalidMessage = "";
isValid = true;
}
else {
$scope.FileInvalidMessage = "Selected file is Invalid. (only file type png, jpeg and gif and 512 kb size allowed)";
}
}
else {
$scope.FileInvalidMessage = "Image required!";
}
$scope.IsFileValid = isValid;
};
This is my file submit button Code
$scope.SaveFile = function () {
$scope.IsFormSubmitted = true;
$scope.Message = "";
$scope.ChechFileValid($scope.SelectedFileForUpload);
if ($scope.IsFormValid && $scope.IsFileValid) {
FileUploadService.UploadFile($scope.SelectedFileForUpload, $scope.FileDescription).then(function (d) {
alert(d.Message);
ClearForm();
}, function (e) {
alert(e);
});
}
else {
$scope.Message = "All the fields are required.";
}
};
This is my factory code
fac.UploadFile = function (file, description) {
var formData = new FormData();
formData.append("file", file);
formData.append("description", description);
var defer = $q.defer();
return $http({
url: 'http://localhost:59838/Api/Home/Sales',
data: JSON.stringify(formData),
headers: { 'content-type': 'application/json' },
transformRequest: angular.identity,
method: 'POST',
})
.success(function (d) {
defer.resolve(d);
})
Here im getting Error as angular.js:15018 Possibly unhandled rejection: {"data":{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:59838/Api/Home/Sales'.","Message
You are getting the $http(...).success is not a function(…)
because the ".success" method has since been deprecated, use ".then" instead. More info on the following link Check Deprecation notice
As for the second error, it could be the result of improper URI, maybe your route is expecting a query parameter, ie : http://localhost:59838/Api/Home/Sales?XXXX, check the full error for more infos
ie : (No HTTP resource was found that matches the request URI ..."
(parameter XXXX is mandatory))

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

Can't figure out where to set {responseType: 'arraybuffer'}

I have been trying to set the responseType to 'arrayBuffer' in the following code, but I keep getting Failed to load pdf document
var resource = ApiService.getResource('/cases/report');
resource.get({caseId: self.CaseID,responseType:'arraybuffer'},function(data){
var file = new Blob([data], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
I have tried putting {responseType: 'arraybuffer'} in the getResource method along with a various other places in the get method, but I get the error Failed to Load Pdf Document
I also tried adding it here like:
var resource = $resource('url', {},{responseType: 'arraybuffer'});
but this doesn't work as well
Full code:
function getResource(endpoint) {
var resource = $resource(endpoint, null);
return wrapActions(resource);
}
function wrapActions(resource) {
var wrappedResource = resource;
for (var i = 0; i < self.actions.length; i++) {
self.wrapAction(wrappedResource, self.actions[i]);
}
// return modified copy of resource
return wrappedResource;
}
function wrapAction(resource, action) {
// copy original action
resource['_' + action] = resource[action];
// create new action wrapping the original and sending token
resource[action] = function (data, success, error) {
data = data || {};
return resource['_' + action](
angular.extend({}, data),
function (response) {
handleSuccess(response, success);
},
function (response) {
handleError(response, error);
}
);
};
}
function handleSuccess(response, callback) {
if (callback) {
callback(response);
}
}
function handleError(response, callback) {
if (typeof response.status !== 'undefined') {
switch (response.status) {
case '403' :
case 403 :
case '401' :
case 401 :
handle401();
return;
}
}
if (callback) {
callback(response);
}
}
function handle401() {
if ($state.current.name != 'login') {
AuthService.setRedirect($state.current.name, $stateParams);
}
AuthService.logout();
$state.go('login');
}
}

Download file with Angular and Django

I have a table containing a list of files fetched from the server. I also have a button, that downloads the selected file. So I made a function which call a service and it opens the response (the file) in a new window, so the user can download it.
Controller:
$scope.download = function() {
if ($scope.cancelPromise) {
$scope.cancelPromise.resolve();
}
$scope.cancelPromise = $q.defer();
UserFileSrv.downloadFile.download(
{
fileId: $scope.selectedFile.id
},function(data) {
if (data) {
toaster.pop('success', 'Success', 'success');
window.open(data);
}
}, function(error) {
if (error) {
toaster.pop('error', 'Error', error);
}
}
);
};
The service:
angular.module('app').factory('UserFileSrv', ['$resource', function($resource) {
var userFile = {
downloadFile: $resource('my_url/:fileId/?', {
fileId: '#fileId'
}, {
download: {
method: 'GET',
isArray: false
}
})
};
return userFile;
}]);
The browser shows the 'success' toaster, but it opens a window which contains this string: Cannot GET /%5Bobject%20Object%5D
Note: the Content-Type of the response is: application/json
It seems that you try to pass the downloaded content to the window.open function.
window.open accept the url as the first argument.
You can solve your problem in two cases:
1) Form the url to the resource (ex: 'my_url/12343') and pass it to the window open. But make sure that your server returns your response with header Content-Disposition=attachment;fileName=someFileName. It will force the browser to process the response as an attachment.
2)Otherwise you can use Blob. (it won't work in IE 9 or less)
https://developer.mozilla.org/en-US/docs/Web/API/Blob
Instead of windows.open you can make the following:
function downloadBlob(fileName, blob){
//IE case
if (!!window.navigator.msSaveBlob){
window.navigator.msSaveBlob(blob, fileName);
return;
}
//create url
var url = URL.createObjectURL(blob);
//create invisible acnhor, to specify the file name
var a = document.createElement('a');
document.body.appendChild(a);
a.style = "display: none";
a.href = url;
a.download = fileName;
a.click();
setTimeout(function(){
URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 100);
}
var data = {x: 1, y:2, name: 'abc'};
var blob = new Blob([JSON.stringify(data)], {type : 'octet/stream'});
downloadBlob('myData.json', blob)
The full solution which shows how to download blobs with ngResource is here

Resources