【问题标题】:Image File path to server not C: drive MVC5服务器的图像文件路径不是 C:驱动器 MVC5
【发布时间】:2017-08-31 07:39:08
【问题描述】:

我有一个上传图像的应用程序,我正在尝试获取存储在服务器上而不是我的 C:drive 上的路径。下面是控制器中的代码:

 if (ModelState.IsValid)
        {

        if (file != null)
        {
            string ImageName = System.IO.Path.GetFileName(file.FileName);
            string physicalPath = Server.MapPath("~/Images/");

            try
            {
                if (!Directory.Exists(physicalPath))
                    Directory.CreateDirectory(physicalPath);

                string physicalFullPath = Path.Combine(physicalPath, ImageName);

                file.SaveAs(physicalFullPath);

                customer.CustomerLogo = ImageName;
                customer.CustomerLogoPath = physicalFullPath;
                db.Customers.Add(customer);
                db.SaveChanges();
            }
            catch(Exception e)
            {
                return View("Error",e.Message );
            }
        }
        return RedirectToAction("Index");

    }
    return View(customer);
}

它目前是这样存储的(见上图)我需要路径为“admin.loyaltyworx.co.za\Images\jeep.jpg”我怎样才能做到这一点?

【问题讨论】:

  • 一个可能重复的问题。请检查以下question
  • 您接受了一个完全错误的答案。您需要使用Server.MapPath("~/Images/");,否则当您尝试阅读图像时,您将永远无法访问该图像(并且您只能看到该路径,因为您在本地计算机上创建了图像,当然您一旦发布就不会访问应用程序)。
  • @StephenMuecke,我接受的答案我当然尝试过,即使在我发布后它也有效。
  • 它对路径进行硬编码。不要那样做!
  • 啊,我明白了,当我将其保留为 Server.MapPath("~/Images/") 时,它没有保存到服务器上,并且一旦发布就无法读取。您对更好的解决方案有什么建议吗?

标签: c# image entity-framework asp.net-mvc-5


【解决方案1】:

使用

string physicalPath = "c:\\admin.loyaltyworx.co.za\\Images";

代替

string physicalPath = Server.MapPath("~/Images/");

【讨论】:

  • 我不希望它存储在我的 C 盘上,直接存储到服务器上
  • 我不明白,网站在服务器上吗?然后它将使用服务器的驱动器C:
  • 我试过你的方法,它返回一个错误:'c:/admin.loyaltyworx.co.za/Images' is a physical path, but a virtual path is expected
  • @Unicorn_Girl 我更正了我的答案。请看一下。
  • 你改变了什么?一样的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
  • 2011-10-01
  • 2013-02-23
相关资源
最近更新 更多