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

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

对于我的观点,我使用它

@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype="multipart/form-data" })) {   } 

对于我的控制器,我使用它

 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/")来获取绝对路径(例如C:/的Inetpub / wwwroot的/ MyApp的/ add_data工具/ MyFile.txt的)。

出于安全原因,URL 无法直接访问App_Data文件夹的内容 。 所有的配置,数据库都存储在那里,所以它是相当明显的原因。 如果您需要通过URL访问上传的文件 – 将其上传到其他文件夹。

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

万一它可以帮助任何人,这是一个简单的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(); } 

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

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

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