2016-05-30 83 views
0

我首次在網絡服務器上傳MVC網站。除了文件上傳選項,一切運行良好。每當我試着上傳文件,它會提示我這個錯誤:無法在mvc中上傳文件

The SaveAs method is configured to require a rooted path, and the path '' is not rooted.

錯誤的詳細信息以某種方式表明我我的本地機器上創建我的項目的路徑。

System.Web.HttpException (0x80004005): The SaveAs method is configured to require a rooted path, and the path '' is not rooted. at Printrpk.Controllers.ProductController.Create(ProductModels product) in C:\Projects\Carting\Carting\Carting\Controllers\ProductController.cs:line 145

我已經嘗試了多種方法來檢查我的代碼是否錯誤,但是我無法使它工作。

這是我下寫成的創建動作的時候,不上傳任何圖片

foreach (string fileName in Request.Files) 
{ 
    HttpPostedFileBase file = Request.Files[fileName]; 
    fName = file.FileName; 
    if (file != null && file.ContentLength > 0) 
    { 
     var originalDirectory = new DirectoryInfo(string.Format("{0}images", Server.MapPath(@"/"))); 
     var pathString = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ProductImages"); 
     var filename = Path.GetFileName(file.FileName); 

     bool isExists = System.IO.Directory.Exists(pathString); 
     if (!isExists) 
     { 
      System.IO.Directory.CreateDirectory(pathString); 
     } 

     path = string.Format("{0}//{1}", pathString, filename); 
     file.SaveAs(path); 
    } 
} 

該控制器正常工作。我檢查了我的web.config,它已經指向Web服務器。

這包括在Create查看

<input name="file" type="file" multiple /> 

而且我已經有針對性的文件夾在我的基礎文件夾

+0

你檢查AppDomain.CurrentDomain.BaseDirectory價值? – DanielVorph

+3

使用'Server.MapPath()' - 例如'var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath(「〜/ ProductImages」),fileName); file.SaveAs(路徑);' –

+0

@StephenMuecke我已經試過這個。不起作用。奇怪 – ashhad

回答

3

使用Server.MapPath()獲得對應於虛擬路徑的物理路徑。假設你的應用程序包含一個名爲Images

var fileName = Path.GetFileName(file.FileName); 
var path = Path.Combine(Server.MapPath("~/Images/ProductImages"), fileName); 
file.SaveAs(path); 

附註一個文件夾包含一個名爲ProductImages子文件夾,然後:考慮添加參數IEnumerable<HttpPostedFileBase> file交給你,讓它與選定的文件(或更好的結合POST方法,包括如在您的視圖模型的屬性),而不是使用Request.Files