Hello everyone, I am trying to upload an image in asp.net mvc 5 and save it to a database, until now I have copied my file in a folder, and I'm trying to save that route to my database, this is my controller code...
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var model = new ImageModel();
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Uploads"), fileName);
model.ImageServerPath = path;
file.SaveAs(path);
db.images.Add(model);
db.SaveChanges();
}
ViewBag.Message = "Upload Successful";
return RedirectToAction("Index");
}
catch (Exception e)
{
ViewBag.Message = "Upload Failed";
return RedirectToAction("Upload");
}
}
In my view the only thing that I have is a file input, and a button, and this is my model code...
public class ImageModel
{
[Key]
public int Id { get; set; }
public string ImageServerPath { get; set; }
}
And know, my question is, How is the best way to do this?.
Besides, I need to show all the images in my index, but that doesn't work either, don't show nothing, only thumbnails from bootstrap with the alt text inside of it, how can I get the route of my uploaded files, and show the content of the image in that route in my index file?, here is my code...
@model IEnumerable<ArtStore.Models.ImageModel>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
@foreach (var item in Model)
{
string path = item.ImageServerPath;
<img src="@item.ImageServerPath" alt="Blah" />
}
what i'm not doing here?