【问题标题】:Downloading a file using C# in a MVC project?在 MVC 项目中使用 C# 下载文件?
【发布时间】:2015-10-13 02:54:29
【问题描述】:

第一次发帖,如果我犯了任何错误并且不遵守指南,请纠正我。

所以我自己从事 MVC 项目。创建一个将文件分发给注册用户的服务器。我有一些 HTML 经验,所以我尝试使用它来下载文件但不能。我让浏览器尝试下载该文件,但立即显示该文件找不到或不存在。我有一种感觉,因为 IIS 不允许客户端访问文件系统。当然这只是一个猜测。如果这有所作为,我将使用 Microsoft Visual Studio 2015 作为我的 IDE。这是代码。

@model MainApplication.Models.IndexViewModel
@{
  ViewBag.Title = "Download";
 }

<h2>@ViewBag.Title</h2>

<p class="text-success">@ViewBag.Message</p>

<div>

<ul>
    @{
        string dirPath = "\\Users\\hippiewho\\Documents\\Visual Studio 2015\\Projects\\Web Application\\MainApplication\\Views\\Download";
        string dirDownPath = "..\\Download\\";
        Response.ClearContent();
        Response.Clear();
        System.Web.MimeMapping.GetMimeMapping("w3logo.jpg");
    }
    @{
        List<string> dirs = new List<string>(Directory.EnumerateFiles(dirPath));
        foreach (var dir in dirs)
        {
            <li><a class="btn-block" href="@dirDownPath@dir.Substring(dir.LastIndexOf("\\") + 1)" download >@dir.Substring(dir.LastIndexOf("\\") + 1)</a></li>
        }
    }
    </ul>
</div>

控制器除了 view() 函数和下载的 ViewBag 标题外没有太多内容。

【问题讨论】:

  • 要在 MVC 中获取文件,您的控制器中应该有一个返回 FileResult 的操作方法。此外,您可能不应该使用绝对路径,尤其是在视图中。相反,使路径与站点根目录相关,或者将路径定义为配置的一部分并将其作为模型的一部分传递给视图。
  • 在 SO 和其他任何地方都有很多类似的问题 - bing.com/search?q=c%23+asp.net+mvc+downloaad+file。示例您已显示您可能没有尝试查找现有示例的提示(因此帖子可能会因“未显示研究”而遭到反对)。

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


【解决方案1】:

正如 Mason 所说,您可以从您的操作方法返回一个 FileResult。

例子

public FileResult Download()
{
    string examplePathToFile = Server.MapPath("~/Downloads/Image.jpg");
    string exampleMimeType = "image/jpeg";

    return new FileStreamResult(new FileStream(examplePathToFile, FileMode.Open, FileAccess.Read), exampleMimeType);
}

https://msdn.microsoft.com/en-us/library/system.web.mvc.filestreamresult(v=vs.118).aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2016-06-12
    相关资源
    最近更新 更多