In an ASP.NET MVC application, file is successfully saved to a folder and its URL is saved to SQL database. Having problem in loading file in a browser from folder using this URL. Code implementation is:
[HttpPost]
[ActionName("UploadPhoto")]
public ActionResult UploadPhoto(HttpPostedFileBase photoPath)
{
var fileName = Path.GetFileName(photoPath.FileName);
string path;
if (photoPath.ContentLength > 0)
{
path = Path.Combine(Server.MapPath("~/Images/photos"), fileName);
photoPath.SaveAs(path);
return RedirectToAction("CreateWithImage", new { path = path });
}
return View();
}
public ActionResult CreateWithImage(string path)
{
employee em = new employee();
em.districts = new SelectList(hc.districts, "name", "name");
em.photoPath = path;
return View(em);
}
file (image) is rendered in a view as:
@model HRMS.Models.employee
<dd>
@Html.Image(@Model.photoPath)
</dd>
Extension method implementation for @Html.Image is:
namespace HRMS.CustomeHTMLHelper
{
public static class CustomHtmlHelper
{
public static IHtmlString Image(this HtmlHelper helper,string src)
{
TagBuilder tb = new TagBuilder("img");
tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}
}
}
When View is called, I see a broken link for the image. HTML(with correct file path) for the loaded page (View) is seen as:
<dd>
<img src="/App_Data/photos/1.png" />
</dd>
When I try to run the physical path to the image in the browser i.e., <b>Requested URL</b> http://localhost:57852/App_Data/photos/1.png, it is throwing HTTP Error 404.8 - Not Found Error.
Where could I be wrong? Please help.
ViewBag.upload = "Success! Photo was uploaded successfully.";- your redirecting so that will do nothing. And removeTempData["filePath"] = fpath;andstring fp = Convert.ToString(TempData["filePath"]);and use `em.photoPath = path;string path; before theif` block and use justpath = Path.Combine(...);inside the loop. Then deletestring fpath = "~/App_Data/photos/" + fileName;and usereturn RedirectToAction("CreateWithImage", new { path = path });404.8error usually means your being denied requests to files in_AppData(which is the default). Suggest you create another folder in your app (say\Images\photos), copy the file there and try it with that path.