c# - 如何在使用 Razor 将文件上传到 MVC 3 中的 App_Data/Uploads 后查看文件?

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

我是 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" />
}

对于我的 Controller ,我使用这个

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 作为我文件的链接。我希望我说得够清楚了。任何帮助将不胜感激。 谢谢

最佳答案

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

出于安全原因,

无法通过 URL 直接访问 App_Data 文件夹的内容。所有配置、数据库都存储在那里,所以原因很明显。如果您需要通过 URL 访问上传的文件 - 将其上传到其他文件夹。

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

关于c# - 如何在使用 Razor 将文件上传到 MVC 3 中的 App_Data/Uploads 后查看文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7302253/

相关文章:

c# - 调试时在 Visual Studio 中使用 LINQ

c# - .Net DrawString 字体引用在调用后发生变化

java - 如何上传 CSV 文件,然后自动将数据插入数据库?

asp.net-mvc-3 - 在 Razor/MVC3 中显示来自数据库的图像

java - struts如何设置上传文件的具体名称

c++ - 如何在 vc 中停止正在进行的上传

c# - 使用 JpegBitmapEncoder 将 WPF BitmapImage 与 Base64 相互转换,无法加载 JPG 文件

c# - 运行 CMD 和 ffmpeg Windows 窗体

asp.net-mvc-3 - MVC3 操作中的 HTML5 视频无法正常工作

mysql - 如何在 Orchard CMS 1.3.10 中使用 MySQL 数据库?