2017-08-17 83 views
0

在MVC中,我们使用了以下代码来下载文件。在ASP.NET核心中,如何实现这一点?如何在ASP.NET Core中下载文件

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(); 

回答

1

你的控制器应返回IActionResult,并使用File方法,比如这个:

[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); 
} 
1

你可以试试下面的代码来下载文件。它应该返回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); 

}