【问题标题】:ActionLink and method to download file from ASP.net MVC project [duplicate]ActionLink 和从 ASP.net MVC 项目下载文件的方法 [重复]
【发布时间】:2018-04-17 23:37:15
【问题描述】:

我在 Visual Studio 中有一个 Asp.net 核心 MVC 项目。我在项目中添加了一个名为“下载”的文件夹,并将“ReadMe.txt”文件添加到该文件夹​​中。我正在尝试使用户能够下载文件。在我看来,我有:

@Html.ActionLink("Readme.txt", "ReadMe", "Download")

这会调用 DownloadController 中的 ReadMe 操作。但是,过去一个小时我一直在努力编写返回文件的操作方法。

我认为应该这样做,但 IDE 无法识别服务器,我找不到导入来解决它。我尝试过使用 System.Web,但它不起作用。

public FileResult ReadMe()
{
    string filename = "ReadMe_2.1.txt";
    string serverpath = Server.MapPath("~/Download/");
    string filepath = serverpath + filename;

    return File(filepath, System.Net.Mime.MediaTypeNames.Application.Octet, filename);
}

有什么建议吗?

【问题讨论】:

  • Server 在 core-mvc 中不存在。参考this answer 一个选项
  • 太棒了。这正是我所需要的。抱歉我之前没找到。

标签: c# download asp.net-core-mvc


【解决方案1】:

感谢 Stephen Muecke 指导我解决这个类似问题: Download File using MVC Core

由于我自己努力寻找答案,我还在此处提供了解决我的问题的代码,希望它可以帮助遇到类似情况的其他人:

public FileResult ReadMe()
{
    var fileName = $"ReadMe_2.1.txt";
    var filepath = $"Download/{fileName}";
    byte[] fileBytes = System.IO.File.ReadAllBytes(filepath);
    return File(fileBytes, "application/txt", fileName);
}

感谢https://stackoverflow.com/users/5528313/vague

【讨论】:

    【解决方案2】:

    查看

    @foreach (var item in ViewData.Model)
        {
            @Html.ActionImage("Home", "DownloadFile", new { filename = item }, "~/Images/Standard/downloadIcon.png")
        }
    

    控制器

    public ActionResult DownloadFile(string filename)
        {
            if (Path.GetExtension(filename) == ".pdf")
            {
                string fullPath = Path.Combine(Server.MapPath("~/Images/ArticleOfAssociations"), filename);
                return File(fullPath, "ArticleOfAssociations/pdf");
            }
            else
            {
                return new HttpStatusCodeResult(System.Net.HttpStatusCode.Forbidden);
            }
        }
    

    【讨论】:

    • 阅读问题(asp.net-core-mvc中没有Server.MapPath()!)
    猜你喜欢
    • 2011-01-04
    • 1970-01-01
    • 2015-02-18
    • 2016-05-23
    • 1970-01-01
    • 2017-05-16
    • 2023-03-03
    • 2011-02-08
    • 2020-08-13
    相关资源
    最近更新 更多