Reputation: 1
In an ASP.NET MVC
application, file
is successfully saved to a folder and its URL
is saved to SQL database
. URL
is saved in an Absolute URL
form i.e., (D:\Visual Studio Projects\HRMS\HRMS\App_Data\photos\5.png). 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);
if (photoPath.ContentLength > 0)
{
var path = Path.Combine(Server.MapPath("~/App_Data/photos"), fileName);
photoPath.SaveAs(path);
}
ViewBag.upload = "Success! Photo was uploaded successfully.";
string fpath = Path.Combine(Server.MapPath("~/App_Data/photos"), fileName);
TempData["filePath"] = fpath;
return RedirectToAction("CreateWithImage", new { path = fpath });
}
public ActionResult CreateWithImage(string path)
{
employee em = new employee();
em.districts = new SelectList(hc.districts, "name", "name");
string fp = Convert.ToString(TempData["filePath"]);
em.photoPath = fp;
return View(em);
}
file (image) is rendered in a view as:
@model HRMS.Models.employee
<dd>
<img src="@Url.Content(@Model.photoPath)" />
</dd>
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="D:\Visual Studio Projects\HRMS\HRMS\App_Data\photos\5.png" />
</dd>
Can someone note the problem and guide accordingly?
Upvotes: 0
Views: 3986
Reputation: 2280
Remove the Image from App_Data folder because it is a hidden Segment section and hence the application is denied access to that folder.
Just Create a New Folder outside the app_data folder.
You can now access the image in two ways
../photos/5.png
Helpful Tip:Once you run the application you can use the absolute path in the browser to see if the image is accessible. If you are not able to access it will tell u the physical path where it is trying to search that image. With this you will be easy able to fix the absolute path.
Upvotes: 0
Reputation: 182
Replace your existing line-
TempData["filePath"] = fpath;
With
TempData["filePath"] = Url.Content("~/App_Data/photos/" + fileName);
Upvotes: 0
Reputation: 219117
This isn't a URL, it's a file system path:
D:\Visual Studio Projects\HRMS\HRMS\App_Data\photos\5.png
The two are very different things. You might be able to get away with a file://
URL, maybe:
file://D/Visual Studio Projects/HRMS/HRMS/App_Data/photos/5.png
But it would make infinitely more sense to just use an actual URL. Something like:
/App_Data/photos/5.png
(Or an absolute URL, something relative to the current page, etc.)
So saving the path might look something more like this:
var path = VirtualPathUtility.ToAbsolute("~/App_Data/photos/" + fileName);
Upvotes: 1