In MVC, we have used following code to download a file. In ASP.NET core, how to achieve this?
HttpResponse response = HttpContext.Current.Response;
Here is my Medium article, describing everything step by step (it also includes a GitHub repo): https://medium.com/@tsafadi/download-a-file-with-asp-net-core-e23e8b198f74
Any ways this is how the controller should look like:
[HttpGet]
public IActionResult DownloadFile()
{
// Since this is just and example, I am using a local file located inside wwwroot
// Afterwards file is converted into a stream
var path = Path.Combine(_hostingEnvironment.WebRootPath, "Sample.xlsx");
var fs = new FileStream(path, FileMode.Open);
// Return the file. A byte array can also be used instead of a stream
return File(fs, "application/octet-stream", "Sample.xlsx");
}
Inside the view:
$("button").click(function () {
var xhr = new XMLHttpRequest();
xhr.open("GET", "Download/DownloadFile", true);
xhr.responseType = "blob";
xhr.onload = function (e) {
if (this.status == 200) {
var blob = this.response;
/* Get filename from Content-Disposition header */
var filename = "";
var disposition = xhr.getResponseHeader('Content-Disposition');
if (disposition && disposition.indexOf('attachment') !== -1) {
var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
var matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
}
// This does the trick
var a = document.createElement('a');
a.href = window.URL.createObjectURL(blob);
a.download = filename;
a.dispatchEvent(new MouseEvent('click'));
}
}
xhr.send();
});