Hi everyone,
I can store pictures in the file system and store the images names in the database, like this: Image1.JPG. But now I want to display the pictures after uploading.
I have this for view:
<div id="tabs-3">
@using (Html.BeginForm("UploadMorePhotos", "Account", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<div class="form-field">
<p>Select pictures:</p>
<div class="upload-container">
<div class="upload">
<input type="file" name="files" value="" multiple="multiple" id="file1" />
<img src="@Url.Content("~/images/deleteButton.png")" alt="Remove picture." />
</div>
</div>
</div>
<div class="form-field">
<input type="submit" value="Upload" />
</div>
<br />
foreach (var item in Model.LolaBikePhotos )
{
@*@Html.DisplayFor(modelItem => item.ImagePath)*@
Html.Image("~/App_Data/uploads", item.ImagePath, new { width = 200, height = 150 });
<img width="200" height="150" src="@Url.Action("UploadMorePhotos", "Account", new { UserProfileID = Model.Id })">
}
}
</div>
The Jquery:
<pre lang="Javascript">
var currentImage = 1;
$("body").on("change", "input[name='files']", function () {
var pathToRemoveIcon = "@Url.Content("~/Images/deleteButton.png")";
currentImage = currentImage + 1;
var htmlToAppend = '<div class="upload"><input type="file" name="files" id="file' + currentImage + '" /><img src="' + pathToRemoveIcon + '" alt="Remove picture." /></div>';
$('.upload-container').append(htmlToAppend);
}).on("click", ".upload img", function () {
if ($(this).parent().siblings().length > 0) {
$(this).parent().remove();
}
});
and the action method:
[HttpPost]
public ActionResult UploadMorePhotos(UserProfile user, IEnumerable<HttpPostedFileBase> files)
{
foreach (var file in files)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/profile" + @"\" + fileName.Replace('+', '_')));
file.SaveAs(path);
if (ModelState.IsValid)
{
string username = User.Identity.Name;
user = db.userProfiles.FirstOrDefault(u => u.UserName.Equals(username));
user.Image = new byte[file.ContentLength];
file.InputStream.Read(user.Image, 0, file.ContentLength);
user.ImageMimeType = file.ContentType;
db.Entry(user).State = EntityState.Modified;
if (user != null)
{
var lolaphoto = new LolaBikePhoto
{
UserProfileID = user.Id
};
db.lolabikerPhotos.Add(lolaphoto);
lolaphoto.ImagePath = fileName;
}
}
db.SaveChanges();
}
}
return Redirect(Url.Action("Edit", "Account") + "#tabs-3");
}
So everything goes allright, the images are stored as imagespath in the tabel: LolabikePhoto and the Images are saved in the folder: Images/Profile. But ofcourse the images have to be shown. I try it like this:
foreach (var item in Model.LolaBikePhotos )
But the images are broken.
Thank you
ahh, I found the solution, it has to be like this:
<img src="~/Images/profile/@item.ImagePath" alt="" height=150 width=200 />