使用MVC Core下载文件 [英] Download File using MVC Core
问题描述
我找不到使用MVC Core下载文件的参考.
I cannot find a reference to downloading a file using MVC Core.
我们只有一个exe文件供会员从我们的网站下载.过去我们放
We have a single exe file for members to download from our website. In the past we have put
<a href=(file path)> Download < /a>
供我们的用户单击.我想按照
<a href=(file path)> Download < /a>
for our users to click. I would like to do something equivalent in MVC Core along the lines of
<a href=@ViewData["DownloadLink"]> Download < /a>
使用DownloadLink填充文件路径.
with DownloadLink populated with the file path.
public class DownloadController : Controller
{
[HttpGet]
public IActionResult Index()
{
ViewData["DownloadLink"] = ($"~/Downloads/{V9.Version}.exe");
return View();
}
}
`
链接<a href=@ViewData["DownloadLink"]> Download < /a>
获取正确的路径,但是单击时仅在地址栏中呈现该路径.有没有设置下载链接的简单方法?
The link <a href=@ViewData["DownloadLink"]> Download < /a>
gets the correct path, but when clicked only renders the path in the address bar. Is there a simple way to set a download link?
推荐答案
I used this answer posted by @Tieson T to come up with this solution
public FileResult Download()
{
var fileName = $"{V9.Version}.exe";
var filepath = $"Downloads/{fileName}";
byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
return File(fileBytes, "application/x-msdownload", fileName);
}
现在是视图
<a asp-action="Download" asp->
Download
@Ageonix关于不要求〜进入wwwroot也是正确的
@Ageonix was also correct about not requiring the ~ to get to wwwroot
这篇关于使用MVC Core下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!