I am attempting to download a PDF file when a certain page loads in my MVC app. I have the following JS code that fires when the document is ready:
function downloadTripReport() {
$.ajax({
url: '/CompanyHomepage/Download?tripReportId=21',
success: function (data) {
var blob = new Blob([data]);
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "TripReport.pdf";
link.click();
}
});
}
I actually got this solution from this SO post.
The following MVC method is being called:
public FileResult DownloadTripReport(int tripReportId)
{
try
{
var userId = this.TripReportData.GetItem(tripReportId).UserId;
var pdf = this.AzureStorage.RetrieveBlob(this.GetAzureContainerName(userId),
this.GetAzureTripReportBlobName(tripReportId));
return File(pdf, "application/pdf", "TripReport.Pdf");
}
catch (Exception exception)
{
...
}
}
Essentially this method retrieves a PDF from Azure storage and sends it back to the calling client. This code works correctly. I know this because it's being called in other ways and it correctly sends a PDF to the client that can then be viewed.
The problem is this. When the AJAX call is made, a PDF file is downloaded to the client. But when the PDF is clicked on, the OS says the format is incorrect (i.e, it's not a PDF). I've checked the size of the downloaded file and it is correct. But, for some reason, the OS does not think it's a valid PDF. So, I'm guessing the issue has to be with the AJAX call.