2011-09-04 30 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(); 
}