2016-05-30 79 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