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

Rob*_*ert 5 c# file-upload view razor asp.net-mvc-3

我是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" />
}
Run Code Online (Sandbox Code Playgroud)

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

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");        
  }
} 
Run Code Online (Sandbox Code Playgroud)

我的模特是

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; }
}
Run Code Online (Sandbox Code Playgroud)

问题是我想将文件上传到数据库,然后将WebPath作为我文件的链接.我希望我做得足够清楚.真的很感激任何帮助.谢谢

Pio*_*myd 10

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

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

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


Adr*_*arr 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();
}
Run Code Online (Sandbox Code Playgroud)