我的ASP.NET MVC网站的根目录中有一个 ImageUpload 文件夹,该文件夹运行在Windows上并托管在AWS上。
显示图像时,我需要这样的东西:
<img src="/ImageUpload/MyImage.jpg" alt="">
上传图像时,我需要一条物理路径...
string fullPath = System.IO.Path.Combine("C:\\MyWebsiteRoot\\ImageUpload", MyImage.jpg);
file.SaveAs(fullPath);
我要将路径放入我的web.Config:
<!-- if I use a url path, the save won't work -->
<add key="ImageUploadPath" value="/ImageUpload"></add>
<!-- if I use physical path, the display won't work -->
<add key="ImageUploadPath" value="C:\\MyWebsiteRoot\\ImageUpload"></add>
是否可以以既可以用作物理路径又可以用作url路径的方式在Web.Config中定义 ImageUpload 路径?还是我需要在Web.Config中定义2个不同的变量?
答案 0 :(得分:1)
您只需在应用程序设置中存储图像文件夹(位于应用程序根目录中)的名称,然后将其用于保存和呈现图像
<add key="ImageUploadPath" value="ImageUpload"></add>
,然后在保存上载文件时,读取此值并使用该值构建路径。您可以创建一个类似于"~/ImageUploadPath"
的字符串,并将其传递给Server.MapPath
方法,该方法将返回与您传递给它的虚拟路径相对应的物理文件路径。
var fileName = "yourImageFileName.jpg";
var directory = ConfigurationManager.AppSettings["ImageUploadPath"];
var path = Path.Combine(Server.MapPath("~/" + directory), fileName);
model.Image.SaveAs(path);
渲染图像时,使用相同的方法读取目录名称并渲染图像src
的值。
例如,
public ActionResult Profile(int userId)
{
var user = db.Users.Find(userId);
var vm = new UserProfileVm { FirstName = user.FirstName , Id = user.Id };
vm.ProfileImage = GetImagePath(vm.ImagePath);
return View(vm);
}
private string GetImagePath(string imageName)
{
return ConfigurationManager.AppSettings["ImageUploadPath"] + "/" + imageName;
}
在您看来
@model UserProfileVm
<img src="~/@Model.ProfileImage" alt="@Model.FirstName" />