MVC 3 映像上传路径
本文关键字:路径 映像 MVC | 更新日期: 2023-09-27 18:31:28
我正在尝试上传图像和缩略图。
我已将 web.config 中的上传路径设置为 <add key="UploadPath" value="/Images"/>
当我上传图像时,它会获取应用程序所在的硬盘驱动器和文件夹的完整路径|:
D:'Projects'Social'FooApp'FooApp.BackOffice'Images'image_n.jpg
但我只想/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);
}
}
您需要使用 HttpContext.Current.Server.MapPath。
返回与 Web 服务器上指定的虚拟路径对应的物理文件路径。
您的代码可能如下所示:
Path.Combine(HttpContext.Current.Server.MapPath("~/Images"), fileName);
*编辑 - 我正在添加到您上面提供的代码中。它看起来像这样。
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);
}
}
}
我假设这段代码在你的一个控制器中。你试过吗:
Server.MapPath(yourPath);