Reputation: 4463
I have web api in C# which returns bytes array of PDF file. Here is the C# code
[HttpGet]
[Route("Download")]
public async Task<ActionResult<byte[]>> DownloadFiles(int fileDocumentId)
{
var file = await _fileService.FetchFiles(fileDocumentId);
return file.ArchiveData;
}
This is how I call the web api using Javascript fetch.
function download(id) {
fetch(`https://localhost:xxx/api/file/download?fileDocumentId=11`)
.then(response => {
debugger
return response.json()
})
.then(result => {
debugger
console.log('Success:', result);
var file = new Blob([result], { type: 'application/pdf' });
var fileURL = URL.createObjectURL(file);
window.open(fileURL);
})
.catch(function (error) {
console.log('Request failed', error)
});
}
The above did create and open a pdf file but it is corrupted.
In console.log('Success:', result);
, the output in the console is something like below:
Success: JVBERi0xLjUNCiW1tbW1DQoxIDAgb2JqDQo8PC9UeXBlL0NhdGFsb2cvUGFnZXMgMiAwIFIvTGFuZyhlbi1NWSkgL1N0cnVjdFRyZWVSb290IDI3OCAwIFIvTWFya0luZm88PC9NYXJrZWQgdHJ1ZT4+Pj4NCmVuZG9iag0KMiAwIG9iag0KPDwvVHlwZS9QYWdlcy9Db3VudCAzNS9LaWRzWyAzIDAgUiAxNyAwIFIgMjggMCBSIDMxIDAgUiAzOCAwIFIgNDAgMCBSIDQ0IDAgUiA0NSAwIFIgNDYgMCBSIDQ3IDAgUiA0OCAwIFIgNDkgMCBSIDUxIDAgUiA1MiAwIFIgNTMgMCBSIDU0IDAgUiA1NSAwIFIgNTYgMCBSIDU3IDAgUiA1OCAwIFIgNTkgMCBSIDYwIDAgUiA2MSAwIFIgNjIgMCBSIDYzIDAgUiA2NCAwIFIgNjUgMCBSIDY2IDAgUiA2NyAwIFIgNjggMCBSIDY5IDAgUiA3MCAwIFIgNzEgMCBSIDI2NiAwIFIgMjczIDAgUl0gPj4NCmVuZG9iag0KMyAwIG9iag0KPDwvVHlwZS9QYWdlL1BhcmVud
Since the actual output is too long, I have truncated it here.
After googling more, I also tried the below code which convert the bytes array into arrayBuffer before create the blob. It did create and download the PDF but when I open the PDF, that PDF is also corrupted.
function downloadpdf(pdfUrl) {
debugger
fetch(pdfUrl).then(resp => resp.arrayBuffer()).then(resp => {
const file = new Blob([resp], { type: 'application/pdf' });
const fileURL = URL.createObjectURL(file);
const link = document.createElement('a');
link.href = fileURL;
link.download = "FileName" + new Date() + ".pdf";
link.click();
});
}
downloadpdf('https://localhost:xxx/api/file/download?fileDocumentId=11')
For FetchFiles
method, basically it read the PDF file and convert it into bytes array.
byte[] fileBytes = await File.ReadAllBytesAsync(file);
Upvotes: 0
Views: 5991
Reputation: 7867
Your code returning byte array to JavaScript and you don't need to do that, just return it as FileContentResult
which will write a binary file to the response and the browser will download it as a file even if you call the API directly in the browser.
[HttpGet]
[Route("Download")]
public async Task<ActionResult> DownloadFiles(int fileDocumentId)
{
string filePath = fileDocumentId=11;
var file = await _fileService.FetchFiles(fileDocumentId);
string fileName = "FileName" + DateTime.Now.ToString() + ".pdf";
return File(file.ArchiveData, "application/force-download", fileName);
}
Upvotes: 2