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!
});
Related
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(
.....
]);
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 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 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'
});
},