我有一个用户可以上传其头像的菜单,我想将该文件路径保存在该图像所在的光盘上。
[HttpPost]
public ActionResult ChangePicture(HttpPostedFileBase file)
{
using (EFJugadorRepository jugadorRepository = new EFJugadorRepository())
{
var jugador = jugadorRepository.FindJugadorByEmail(User.Identity.Name);
if (file != null && file.ContentLength > 0)
{
var extension = Path.GetExtension(file.FileName);
string fileName = String.Format("{0}{1}", User.Identity.Name, extension);
var path = Path.Combine(Server.MapPath("~/Public/Avatars"), fileName);
file.SaveAs(path);
using (EFFotografiaRepository fotografiaRepository = new EFFotografiaRepository())
{
var fotografia = fotografiaRepository.FindAllFotografias().SingleOrDefault(f => f.fotCodigo == jugador.jugCodigo);
if (fotografia == null)
{
fotografia = new taFotografia();
fotografiaRepository.CreateNewFotografia(fotografia);
}
fotografia.fotCodigo = (int)jugador.jugCodigo;
fotografia.fotTipo = 0;
//string relativeRootPath = Url.Content("~/Public/Avatars");
string relativeRootPath = "http://localhost:23188/Public/Avatars";
fotografia.fotUrl = String.Format("{0}/{1}", relativeRootPath, fileName);
fotografiaRepository.SaveChanges();
jugador.jugFoto = fotografia.fotCodigo;
jugadorRepository.SaveChanges();
}
}
// redirect back to the index action to show the form once again
return RedirectToAction("CropPicture");
}
}
如果你注意到,我注释掉了一行:
string relativeRootPath = Url.Content("~/Public/Avatars");`
这不起作用,这是可以理解的;我不得不手动输入URI“localhost”。
有没有办法获取根URI并使用它来保存路径?或者有更好的方法吗?
答案 0 :(得分:0)
试试这个:
string path1 = HttpContext.Current.Request.ApplicationPath;
string realPath = HttpContext.Current.Request.MapPath(path1);