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();
}
});
};
Related
$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);
}
I am getting response like
StatusCode: 200, ReasonPhrase: 'OK', Version: 1.1, Content: System.Net.Http.ByteArrayContent, Headers:
{
x-filename: StatementofAccount.pdf
Content-Type: application/octet-stream
Content-Disposition: attachment; filename=StatementofAccount.pdf
}
now i need to use "x-filename: StatementofAccount.pdf" but i am not able to fetch this.
I fill this response to my model like
$scope.dataDetail = response.data;
but when I tried to get
console.log($scope.dataDetail.StatusCode)
or
console.log($scope.dataDetail.Headers.x-filename)
but its showing undefined.
plz get me an idea where i am doing wrong or how to achieve this.
I tried from the following way..plz get me idea where i am wrong.....
c#
....
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
httpResponseMessage.Content = new ByteArrayContent(bytes.ToArray());
httpResponseMessage.Content.Headers.Add("x-filename", fileName);
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
httpResponseMessage.StatusCode = HttpStatusCode.OK;
return httpResponseMessage;
in angularjs
$http({
method: 'post',
url: basePath + '/profile/downloadpdf_fromedit',
// data: JSON.stringify($scope.paginginfostmntaccnt),
responsetype: 'arraybuffer',
headers: {'content-type': 'application/pdf'},
// headers: { 'content-type': 'application/json' }
})
.then(function (response) {
// console.log(response.data);
$scope.dataDetail = response.data;
console.log($scope.dataDetail)
1. var file = new Blob([response.data], { type: 'application/pdf' });
saveAs(file, 'StatementofAccount.pdf');
//url-file:///C:/Users/tushar/Downloads/StatementofAccount.pdf
//failed to load pdf
2.var file = new Blob([response], { type: 'application/pdf' });
var fileurl = URL.createObjectURL(file);
window.open(fileurl);
//url- blob:http://localhost:16311/02f8d85e-74c0-4ccd-b937-22f02cc3866c
//failed to load pdf document
3.
.success(function (data, status, headers, config) {
// any required additional processing here
var results = [];
results.data = data;
results.headers = headers();
results.status = status;
results.config = config;
console.log(results)
$("#loading").hide();
headers = headers();
var filename = headers['x-filename'];
var contentType = headers['content-type'];
if (!filename) {
filename = headers["x-filename"] || 'statementAccount.pdf';
}
var linkElement = document.createElement('a');
try {
var blob = new Blob([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);
$("#loading").hide();
console.log("filename" + filename);
} catch (ex) {
console.log("catch"+ex);
$("#loading").hide();
}
})
//url-file:///C:/Users/tushar/Downloads/statementAccount.pdf
//failed to load pdf document
To access the headers of the response you need to use response.headers instead of response.data the data portion contains body of the response.
I'm trying to download PDF from a WebApi using Angular but the file is only 15 bytes. If I log the data being received from the WebApi it's an arraybuffer with the expected size
The WebApi
[HttpGet]
public HttpResponseMessage MatchRegistrationReport(int matchId)
{
try
{
var gen = new MSReports.Components.MatchRegistration();
byte[] bytes = gen.GeneratePDF(matchId, 10);
var stream = new MemoryStream(bytes);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StreamContent(stream)
//Content = new ByteArrayContent(bytes)
};
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = gen.ReportName + ".pdf"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
return result;
}
catch (Exception ex)
{
Log.Error(ex.Message);
return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
The Angular controller
$scope.Print = function () {
$scope.message = "Downloading";
reportResource.printMatchRegistration($scope.match.Id).then(function (data, status, headers, config) {
var file = new Blob([data], {
type: 'application/csv'
});
//trick to download store a file having its URL
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = 'MatchRegistration.pdf';
document.body.appendChild(a);
a.click();
//$scope.message = "Completed";
}, function (data, status, headers, config) {
$scope.message = "A error occurred";
});
}
and the resource
printMatchRegistration: function (matchId) {
return $http({
method: 'get',
url: this.getApiPath() + "MatchRegistrationReport?matchId=" + matchId,
headers: {
'Content-type': 'application/pdf',
},
responseType: 'arraybuffer'
});
I believe it has something to do with the content-type but can' figure out what.
Hi just found the answer
Change to this
reportResource.printMatchRegistration($scope.match.Id).then(function (response) {
var file = new Blob([response.data], {
type: 'application/pdf'
});
and this
printMatchRegistration: function (matchId) {
var data = { 'matchId': matchId };
return $http({
method: 'get',
url: this.getApiPath() + "MatchRegistrationReport",
params: data,
headers: {
'Content-type': 'application/pdf',
},
responseType: 'arraybuffer'
});
},
I'm using GM, a GraphicsMagick for Node.js package to convert images to pdf on the server, and send them to Angular.js passing a buffered stream like so:
var comm = gm().command('convert')
for (page in pages) {
comm.in('./docs/' + data.nomefile + '[' + pages[page] + ']')
}
comm.density(150, 150).compress('jpeg').stream('pdf', function(err, stdout, stderr) {
if (!err) {
var bufs = [];
stdout.on('data', function(chunk) {
bufs.push(chunk)
});
stdout.on('end', function() {
var buf = Buffer.concat(bufs).toString('base64');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header('content-type', 'application/pdf');
res.send(buf)
})
Unfortunately I'm unable to send to the client more than few pdf pages (depending on their size).
On Angular I decode these images using this service:
$http.get(baseUrl+imageUrl, {responseType: 'arraybuffer'}).
success(function(data) {
var pdfData=Base64Service.ConvertArrayBuffer(data);
cbk(pdfData);
}).
error(function(data, status) {
var err= 'Request failed with status: ' + status;
cbk(err);
});
On the controller:
window.open('data:application/pdf;base64,' + pdfData);
When the limit is exceeded I get only a blank page and nothing else.
Thanks to mscdex suggestion, this is how I managed to properly render all the images:
Server side:
var comm = gm().command('convert')
for (page in pages) {
comm.in('./docs/' + data.nomefile + '[' + pages[page] + ']')
}
comm.density(150, 150).compress('jpeg').stream('pdf', function(err, stdout, stderr) {
if (!err) {
res.header('content-type', 'application/pdf');
stdout.pipe(res)
}
Client Angular.js service:
createPdf: function(imageId, pagesArray) {
$http({
method: 'GET',
cache: false,
url: baseUrl + 'image/createPdf/',
params: {
id: imageId,
pages: JSON.stringify(pagesArray)
},
responseType: "arraybuffer"
}).success(function(pdfData) {
var file = new Blob([pdfData], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
});
}
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