【问题标题】:How to view a file after uploading it to App_Data/Uploads in MVC 3 with Razor?使用 Razor 将文件上传到 MVC 3 中的 App_Data/Uploads 后如何查看文件?
【发布时间】:2011-11-10 06:18:18
【问题描述】:

我是 mvc 新手,遇到了一个问题。我到处寻找答案,但找不到答案,但我很确定有些东西跳过了我。问题是我将文件上传到 App_Data 文件夹后不知道如何访问它。我使用在所有论坛上找到的相同代码:

在我看来,我使用这个

@using (Html.BeginForm("Index", "Home", FormMethod.Post, 
new { enctype="multipart/form-data" }))
{
<input type="file" name="file" />
<input type="submit" value="submit" />
}

对于我的控制器,我使用这个

public class HomeController : Controller
{
// This action renders the form
public ActionResult Index()
{
    return View();
}

// This action handles the form POST and the upload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
    // Verify that the user selected a file
    if (file != null && file.ContentLength > 0) 
    {
        // extract only the fielname
        var fileName = Path.GetFileName(file.FileName);
        // store the file inside ~/App_Data/uploads folder
        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
        file.SaveAs(path);
    }
    // redirect back to the index action to show the form once again
    return RedirectToAction("Index");        
  }
} 

我的模特是

public class FileDescription
{
    public int FileDescriptionId { get; set; }
    public string Name { get; set; }
    public string WebPath { get; set; }
    public long Size { get; set; }
    public DateTime DateCreated { get; set; }
}

问题是我想将文件上传到数据库,然后将 WebPath 链接到我的文件。我希望我说得够清楚。任何帮助将不胜感激。 谢谢

【问题讨论】:

  • 我希望我的数据库只有文件的路径,而不是文件本身。
  • 您能定义一下“查看文件”的含义吗?您想将其显示为链接,还是想显示文件的实际内容?

标签: c# asp.net-mvc-3 file-upload view razor


【解决方案1】:

您可以访问您的文件服务器端(以便从 ASP.NET 应用程序访问其内容) - 只需使用 Server.MapPath("~/App_Data/uploads/&lt;yourFileName&gt;") 获取绝对路径(例如 C:/inetpub/wwwroot/MyApp/Add_Data/MyFile. txt)。

出于安全原因,不能通过 URL 直接访问 App_Data 文件夹的内容。所有配置,数据库都存储在那里,所以很明显为什么。如果您需要通过 URL 访问您上传的文件,请将其上传到其他文件夹。

我猜您需要通过网络访问该文件。在这种情况下,最简单的解决方案是在数据库中为您的文件保留一个文件名(或开头提到的完整绝对路径),并创建一个控制器操作,该操作将采用文件名并返回文件的内容。

【讨论】:

    【解决方案2】:

    如果它对任何人都有帮助,这里有一个 PDF 的简单示例:

    public ActionResult DownloadPDF(string fileName)
    {
        string path = Server.MapPath(String.Format("~/App_Data/uploads/{0}",fileName));
        if (System.IO.File.Exists(path))
        {
            return File(path, "application/pdf");
        }
        return HttpNotFound();
    }
    

    【讨论】:

      【解决方案3】:

      您应该使用通用处理程序来访问文件。 IMO 将图像/文件存储在 App_Data 文件夹中是最佳做法,因为默认情况下它不提供文件。

      当然,这取决于您的需求。如果您根本不关心谁可以访问图像,那么只需将它们上传到 app_data 文件夹之外的文件夹:)

      这一切都取决于您的需求。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-28
        • 2020-06-23
        • 2011-11-20
        • 2015-09-13
        相关资源
        最近更新 更多