2011-09-04 64 views
5

我是mvc的新手,我遇到了一个问题。我搜索了一个答案,我找不到一个答案,但我确信有东西跳过了我。问题是,我不知道如何在将文件上载到App_Data文件夹后访问文件。我用我所有的论坛上发现了同样的代码:如何在将文件上传到App_Data之后查看文件/使用Razor在MVC 3中上传文件?

对于我的看法我用这个

@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成为我的文件的链接。我希望我已经说清楚了。任何帮助真的会被赞赏。 感谢

+0

我想我的数据库只具有文件路径,而不是文件本身。 – Robert

+0

您能否定义“查看文件”的含义,是否要将其显示为链接,还是要显示文件的实际内容? –

回答

10

您可以访问你的文件服务器端(所以访问从ASP.NET应用程序及其内容) - 只需使用Server.MapPath("~/App_Data/uploads/<yourFileName>")得到绝对路径(例如C:/的Inetpub/wwwroot文件/ MyApp的/ add_data工具/ MyFile的。文本)。

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

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

0

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

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

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

8

在情况下,它可以帮助任何人,这里有一个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(); 
}