Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a file in ASP.NET Core?

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();
like image 384
BALA MURUGAN Avatar asked Aug 17 '17 06:08

BALA MURUGAN


2 Answers

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);
}
like image 152
Métoule Avatar answered Nov 07 '22 17:11

Métoule


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);
    
}
like image 34
XamDev Avatar answered Nov 07 '22 16:11

XamDev