[英]Saving images relative to content directory where my site is running in IIS
[英]How to get the relative URI of where my website is running?
我有一个菜单,用户可以在其中上传他们的头像,我想将该文件路径保存在该图像所在的光盘上。
[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并使用它来保存路径? 或者,还有更好的方法?
尝试这个:
string path1 = HttpContext.Current.Request.ApplicationPath;
string realPath = HttpContext.Current.Request.MapPath(path1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.