2014-09-30 133 views
1

我做我的第一個MVC項目爲學校,跑進這個問題:文件上傳到服務器

我建立的公告網頁,用戶可以上傳自己想要出售, 至於什麼圖片據我所知,最佳實踐就是將Image路徑存儲到Db表中,並將文件放入服務器中的文件中。因此,我可以在網頁中檢索該特定圖像。

問題是,我只能在本地計算機中存儲圖像,而不是在我發佈項目的服務器上。

如何將此文件上傳到服務器而不是本地計算機?

這是我的控制器:

public ActionResult CreateAnuncio(HttpPostedFileBase thePic) 
{ 
    if (thePic != null && thePic.ContentLength > 0) 
    { 
     // string filePath = Path.Combine(Server.MapPath("http://example.com/Sites/mvc/classifieds/Images/slider"), Path.GetFileName(Nuevo.id + thePic.FileName)); // Does not Work 

     string filePath = Path.Combine(Server.MapPath("~/Images/slider/"), Path.GetFileName(thePic.FileName)); //Works only for local saving 

     thePic.SaveAs(filePath); 
    } 
    return RedirectToAction("Index"); 
} 

基本上我得到的錯誤是:

http://example.com/Sites/mvc/classifieds/Images/slider'不是有效的虛擬路徑。

這裏查看:

<form id="contact_form" method="post" action="/classifieds/CreateAnuncio" enctype="multipart/form-data"> 
    <input type="file" name="thePic"/> 
    <input type="submit" value="Send"> 
</form> 
+0

我們可以看到發佈到此操作的表單嗎? – spender 2014-09-30 01:26:49

+0

我剛剛發佈了表單...我刪除了一些其他非相關內容 – Cessna 2014-09-30 01:35:31

+0

被評論爲「// string filePath」的行是我放置服務器路徑但不工作的地方。 – Cessna 2014-09-30 01:38:16

回答

2

如果您在同一臺服務器上運行的代碼,您可以使用相對路徑到該文件夾​​。

var filePath = Path.Combine(Server.MapPath("~/classifieds/Images/slider"), 
             Path.GetFileName(Nuevo.id + thePic.FileName)); 

如果是在網絡中的共享位置,但在這裏你部署代碼的服務器訪問,這也應該工作

var filePath = Path.Combine(\\myFileServerName\files\", 
             Path.GetFileName(Nuevo.id + thePic.FileName)); 

在這兩種情況下,確保目錄的權限被更新,以便ASP.NET可以寫入。

右鍵單擊該文件夾,然後轉到屬性 - >安全和更新的權限。

+0

我沒有在IIS中創建任何虛擬目錄,所以我猜這是錯誤「不是有效的虛擬路徑」。來自 – Cessna 2014-09-30 02:24:27

+0

你的第二個建議(保存到網絡共享)通常很難實施,因爲它要求給每個人R/W訪問共享或複雜的模擬設置... – 2014-09-30 02:42:22