In MVC, we have used the following code to download a file. In ASP.NET core, how to achieve this?
HttpResponse response = HttpContext.Current.Response;
System.Net.WebClient net = new System.Net.WebClient();
string link = path;
response.ClearHeaders();
response.Clear();
response.Expires = 0;
response.Buffer = true;
response.AddHeader("Content-Disposition", "Attachment;FileName=a");
response.ContentType = "APPLICATION/octet-stream";
response.BinaryWrite(net.DownloadData(link));
response.End();
Your controller should return an IActionResult
, and use the File
method, such as this:
[HttpGet("download")]
public IActionResult GetBlobDownload([FromQuery] string link)
{
var net = new System.Net.WebClient();
var data = net.DownloadData(link);
var content = new System.IO.MemoryStream(data);
var contentType = "APPLICATION/octet-stream";
var fileName = "something.bin";
return File(content, contentType, fileName);
}
You can try below code to download the file. It should return the FileResult
public ActionResult DownloadDocument()
{
string filePath = "your file path";
string fileName = "your file name";
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
return File(fileBytes, "application/force-download", fileName);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With