【问题标题】:Cannot upload file in mvc无法在mvc中上传文件
【发布时间】:2016-05-30 23:35:34
【问题描述】:

我是第一次在网络服务器上上传 MVC 网站。除了文件上传选项外,一切都运行良好。每当我尝试上传文件时,它都会提示我这个错误:

SaveAs 方法被配置为需要一个根路径,并且该路径 '' 没有root。

错误详细信息以某种方式显示了我在本地计算机上创建的项目的路径。

System.Web.HttpException (0x80004005): SaveAs 方法被配置 要求有根路径,并且路径''没有根。在 Printrpk.Controllers.ProductController.Create(ProductModels 产品) 在 C:\Projects\Carting\Carting\Carting\Controllers\ProductController.cs:line 145

我尝试了多种方法来检查我的代码是否错误,但我无法使其正常工作。

这是我在Create Action

下写的
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-server。

这包含在Create 视图中

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

我的基本文件夹中已经有目标文件夹

【问题讨论】:

  • 您检查过 AppDomain.CurrentDomain.BaseDirectory 的值吗?
  • 使用Server.MapPath() - 例如var fileName = Path.GetFileName(file.FileName); var path = Path.Combine(Server.MapPath("~/ProductImages"), fileName); file.SaveAs(path);
  • @StephenMuecke 我已经尝试过了。不工作。奇怪
  • 您的应用是否包含文件夹ProductImages?而你在使用的时候,path的值是多少?
  • 谢谢@StephenMuecke,我得到了这个问题。你的代码现在可以工作了。我插入了错误的变量。请在下面写下您的答案,以便我投票:)

标签: c# asp.net asp.net-mvc


【解决方案1】:

使用Server.MapPath() 获取对应于虚拟路径的物理路径。假设您的应用包含一个名为 Images 的文件夹,其中包含一个名为 ProductImages 的子文件夹,那么

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

旁注:考虑为您的 POST 方法添加一个参数 IEnumerable&lt;HttpPostedFileBase&gt; file,以便它与所选文件绑定(或者更好的是,将其作为属性包含在您的视图模型中)而不是使用 Request.Files

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 2018-09-29
    • 1970-01-01
    • 2012-05-23
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多