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.
Related
Here I have hard coded fileName but I want to get the filename from my spring service where I have already set the file name in header of http response. How to get the file name at js end.
$http.post('/myrest/rest/getVendorExcelDownload',$scope.exelReportInputDTO,{responseType: 'arraybuffer'})
.success(function(data, status, headers, config){
console.log("inside success");
var fileName = "Vendor_Excel_Reports.xls";
var a = document.createElement("a");
var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
var objectUrl = URL.createObjectURL(blob);
a.href = objectUrl;
a.download = fileName;
a.click();
}).error(function(data){
console.log("inside error");
});
You can try to get filename from header like this ..
var req = {
method: 'POST',
url: '', //your API
headers: {
id: id // get your filename from header
}
}
$http(req)
.then(function mySucces(response) {
//your success code!
},
function myError(response) {
//your error code!
});
I have developed an angular JS web application with PDF file download functionality. It doesn't work in Safari.
$http({
method: 'GET',
url: common.serviceUrl(config.apiServices.usermanuals),
params: { manualId: manualId },
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
headers = headers();
//var test = headers('Content-Disposition');
var filename = headers['x-filename'];
var contentType = headers['content-type'];
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);
} catch (ex) {
console.log(ex);
}
}).error(function (data) {
console.log(data);
});
Please help me find a workaround to this. Thank you
Try using FileSaver
var file = new Blob([data], { type: 'application/pdf;charset=utf-8' });
FileSaver.saveAs(file, filename);
*data is coming from api response,
*filename you can pass as abc.pdf
I want to downlaod exe file using $http, it shows me when I console the data, but I am unable to download it.
$http({
url: url,
method: "GET",
headers: {
'Content-type': 'application/json'
}
}).success(function (data, status, headers, config) {
console.log(data);
window.open(objectUrl);
}).error(function (data, status, headers, config) {
//upload failed
});
Any help would be appreciated.
you can Use response type like responseType: "arraybuffer"
$http({
url: url,
method: "GET",
headers: {
'Content-type': 'application/json'
},
responseType: "arraybuffer"
}).success(function (data, status, headers, config) {
console.log(data);
var file = new Blob([data], { type: 'application/binary' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
var link=document.createElement('a');
link.href=fileURL;
link.download="testing.exe";
link.click();
window.open(objectUrl);
}).error(function (data, status, headers, config) {
//upload failed
});
and use Blob and pass type "application/binary" and create a link to download it.
Given code will help you to download exe file as well as to check
browser compatibility.
var ieEDGE = navigator.userAgent.match(/Edge/g);
var ie = navigator.userAgent.match(/.NET/g); // IE 11+
var oldIE = navigator.userAgent.match(/MSIE/g);
var blob = new window.Blob([data.data], { type: 'application/x-msdownload' });
if (ie || oldIE || ieEDGE) {
var fileName="filename"+'.exe';
window.navigator.msSaveBlob(blob, fileName);
}
else {
var file = new Blob([ data.data ], {
type : 'application/x-msdownload'
});
var fileURL = URL.createObjectURL(file);
var a = document.createElement('a');
a.href = fileURL;
a.target = '_blank';
a.download = "filename"+'.exe';
document.body.appendChild(a);
a.click();
}
//Successfully Downloaded
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 have a POST request for a PDF document in an APIController, here's the code:
Generator pdfGenerator = new Generator();
MemoryStream ms = pdfGenerator.Generate();
var response = new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StreamContent(ms)
};
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "Tag.pdf"
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
when I send my file to angular with a GET request everything works fine and I can download the pdf using:
$window.open('my_url');
A well formed 28K pdf file is created in the download folder.
But when I changed my request to a POST the file is malformed.
var pdfGetter = $resource('my_url', {}, {
sendPDFTag: { method: 'POST', url: 'my_url', responseType: 'arraybuffer' }
});
pdfGetter.sendPDFTag(info, function(data) {
var file = new Blob([data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$window.open(fileURL);;
});
I tried using the FileSaver.js and I get a bad 1K pdf file in my download folder.
pdfGetter.sendPDFTag(info, function(data) {
var file = new Blob([data], { type: 'application/pdf' });
saveAs(file, 'Tag.pdf');
});
What could the problem be?
Thanks
I found the solution to my problem in this question: pdf-js-render-pdf-using-an-arraybuffer-or-blob-instead-of-url
The problem was with the ng-resource that returns a promise instead of the arraybuffer, so you need to transform the data before you process the promise.
Here is the corrected code:
var pdfGetter = $resource(myUrl, {}, {
sendPDFTag: { method: 'POST', url: myUrl + "/getPdfWithPost", responseType: 'arraybuffer',
transformResponse: function(data, headersGetter) {
// Stores the ArrayBuffer object in a property called "data"
return { data : data };
}
}
});
var pdfGetter = pdfGetter.sendPDFTag(info);
pdfGetter.$promise.then(function () {
var data = pdfGetter.data;
var file = new Blob([data], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
$window.open(fileURL);
});
Thank you