Reputation: 327
I'm trying to upload image to my folder and the display it in view. My controller:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("~/images"), pic);
file.SaveAs(path);
ViewBag.Path = path;
}
return View();
}
My view:
@{
ViewBag.Title = "Upload";
}
@using (Html.BeginForm("Upload", "Home", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}
<h2>Upload</h2>
<img src="@ViewBag.path" alt="Image"/>
By doing this, image is not in my view, only alt text. HTML source generated:
<img src="C:\Users\D Stag\Documents\Visual Studio 2012\Projects\Data\Web\images\1232743916lituviai23afp.jpg"/>
Image is saved correctly, it exist in that folder.
Upvotes: 1
Views: 1383
Reputation: 1201
Example Try like this:
<img src="@string.Format("/Image/{0}",pictue._id.ToString())" alt="@pictue.FileName" />
Upvotes: 0
Reputation: 17182
Instead of -
ViewBag.Path = path;
try that this way -
ViewBag.Path = String.Format("/images/{0}", pic); //output should be "~/images/image1.jpg"
UPDATE: There is no need for "~" in the path. Then image displays.
Upvotes: 3