I can download PDF from my code below, however, "The PDF is corrupted" is mentioned when I tried to open pdf file. What problem is it?
I am using
byte[] binFile = File.ReadAllBytes(file_path_with_filename_with_ext);
as SQL parameter which passed through a stored procedure.
C# code
[HttpGet]
public IActionResult DownLoadPdf(int? ID)
{
string sql = #"SELECT ID, PDFReport
FROM [TABLE]"; // which is VARBINARY(MAX) value
byte[] Report = _dbContext.PDFdto.FromSql(sql).AsNoTracking().Where(r => r.ID == ID.ToString()).Select(r => r.PDFReport).FirstOrDefault();
return Json(new { Report });
}
HTML:
$scope.loadPdfClick = function (ID) {
$http({
url: '#Url.Content("~/Report/DownLoadPdf")',
method: "GET",
params: {
"ID": ID
},
headers: {
'Content-type': 'application/json'
},
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
var blob = new Blob([data], { type: "application/pdf" });
var objectUrl = URL.createObjectURL(blob);
var a = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display:none');
a.setAttribute('href', objectUrl);
var filename = "Report_Test.pdf";
a.setAttribute('download', filename);
a.click();
URL.revokeObjectURL(objectUrl);
}).error(function (data, status, headers, config) {
messageAlert("ERROR");
});
PS: using .NET Core 1.1 with Angular
Related
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'
});
},
My angular controller is
app1.controller('kyc_controller', ['$scope', '$http', function($scope, $http)
{
$scope.uploadFile = function(){
var file = $scope.myFile;
var fd = new FormData();
fd.append('file', file);
$http({
method : 'POST',
url: '/GngService/api/GoNoGo/upload_file',
params : {'filename':'pancard'},
data : fd,
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data, status, headers, config) {
console.log('file ' + config.file.name + 'uploaded. Response: ' + JSON.stringify(data));
});
};
}]);
and my server side api method is
#POST
#Path("/upload_file")
#Consumes({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_FORM_URLENCODED})
#Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response upload(#FormDataParam("file") InputStream ins, #FormDataParam("filename") String filename, #FormDataParam("file") FormDataContentDisposition contentDispositionHeader ) throws IOException {
System.out.println(filename);
BufferedImage image = ImageIO.read(ins);
// ImageIO.write(image, "jpg", new File("/../../fileName"));
String result = "{'status' : 'ok'}";
String json = new Gson().toJson(result);
return Response.ok(json.toString(), MediaType.APPLICATION_JSON).build();
}
It shows Unsupported media type...please help me to upload images....thanks in advance