In similar questions, with this code works to download a PDF:
I'm testing with local files (.xlsx, .pdf, .zip) inside the Controller folder.
[HttpGet("downloadPDF")]
public FileResult TestDownloadPCF()
{
HttpContext.Response.ContentType = "application/pdf";
FileContentResult result = new FileContentResult
(System.IO.File.ReadAllBytes("Controllers/test.pdf"), "application/pdf")
{
FileDownloadName = "test.pdf"
};
return result;
}
But when another file?, for example an Excel File(.xlsx) or ZIP File(.zip), testing does not work properly.
Code :
[HttpGet("downloadOtherFile")]
public FileResult TestDownloadOtherFile()
{
HttpContext.Response.ContentType =
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
FileContentResult result = new FileContentResult(System.IO.File.ReadAllBytes("Controllers/test.xlsx"),
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = "otherfile"
};
return result;
}
I also did tests with the following Content-Type:
Getting the same result.
Which is the right way to return any file type?
Thanks for your answers
My (working) solution:
FileInfo
for the generated file's path.This is what is in my Controller:
[HttpGet("test")]
public async Task<FileResult> Get()
{
var contentRootPath = _hostingEnvironment.ContentRootPath;
// "items" is a List<T> of DataObjects
var items = await _mediator.Send(new GetExcelRequest());
var fileInfo = new ExcelFileCreator(contentRootPath).Execute(items);
var bytes = System.IO.File.ReadAllBytes(fileInfo.FullName);
const string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Response.ContentType = contentType;
HttpContext.Response.Headers.Add("Access-Control-Expose-Headers", "Content-Disposition");
var fileContentResult = new FileContentResult(bytes, contentType)
{
FileDownloadName = fileInfo.Name
};
return fileContentResult;
}
And here is what I have in Angular2:
downloadFile() {
debugger;
var headers = new Headers();
headers.append('responseType', 'arraybuffer');
let url = new URL('api/excelFile/test', environment.apiUrl);
return this.http
.get(url.href, {
withCredentials: true,
responseType: ResponseContentType.ArrayBuffer
})
.subscribe((response) => {
let file = new Blob([response.blob()], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });
let fileName = response.headers.get('Content-Disposition').split(';')[1].trim().split('=')[1];
saveAs(file, fileName);
},
err => this.errorHandler.onError(err)
);
}