【发布时间】: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