Dar*_*der 2 c# image path asp.net-mvc-3
我正在尝试上传图片和缩略图.
我已将web.config中的上传路径设置为 <add key="UploadPath" value="/Images"/>
当我上传图像时,它获取应用程序所在的硬盘驱动器和文件夹的完整路径|:
D:\Projects\Social\FooApp\FooApp.BackOffice\Images\image_n.jpg
Run Code Online (Sandbox Code Playgroud)
但我只想要 /images/image_n.jpg
我用的Path.Combine是你认为的原因吗?
我怎么解决这个问题?
这是代码|:\
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
if (fileName != null) originalFile = Server.MapPath(upload_path) + DateTime.Now.Ticks + "_ " + fileName;
file.SaveAs(originalFile);
images.Add(originalFile);
}
}
Run Code Online (Sandbox Code Playgroud)
您需要使用HttpContext.Current.Server.MapPath.
返回与Web服务器上指定虚拟路径对应的物理文件路径.
您的代码可能如下所示:
Path.Combine(HttpContext.Current.Server.MapPath("~/Images"), fileName);
Run Code Online (Sandbox Code Playgroud)
*编辑 - 我正在添加您上面提供的代码.它看起来像这样.
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var uploadPath = "~/Images"; //This is where you would grab from the Web.Config. Make sure to add the ~
if (fileName != null) {
var originalFile = Path.Combine(HttpContext.Current.Server.MapPath(uploadPath), DateTime.Now.Ticks + "_ " + fileName);
file.SaveAs(originalFile);
images.Add(originalFile);
}
}
}
Run Code Online (Sandbox Code Playgroud)