I want to be able to replace my old images with a new. I got one to many relationship between entites -> many images for one product.
If I change images, old are staying in database. They will be never used. After some time the database is able to make huge itself. How to delete these old files ?
public ActionResult Edit(int? id)
{
if (id == null)
{ return new HttpStatusCodeResult(HttpStatusCode.BadRequest); }
Product product = db.Products.Include(p => p.FilePaths).Where(i => i.ProductId == id).Single();
if (product == null)
{ return HttpNotFound(); }
return View(product);
}
[HttpPost]
public ActionResult Edit(int id, IEnumerable<HttpPostedFileBase> uploads)
{
var product = db.Products.Include(p => p.FilePaths).Where(p => p.ProductId == id).Single();
if (ModelState.IsValid)
{
try
{
product.FilePaths = new List<FilePath>();
foreach (var upload in uploads)
{
if (upload != null && upload.ContentLength > 0)
{
var photo = new FilePath
{
FileName = Path.GetFileName(upload.FileName),
FileType = FileType.Photo
};
product.FilePaths.Add(photo);
upload.SaveAs(Path.Combine(Server.MapPath("~/Content/Images"), photo.FileName));
}
}
db.Entry(product).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
catch (RetryLimitExceededException)
{
ModelState.AddModelError("", "Unable to save changes. Contact with administrator.");
}
}
return View(product);
}
My view for Edit() is:
@model Domain.Entities.Product
@using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { enctype = "multipart/form-data" })) {
// code ommited for brevity..
<div class="row">
@Html.Label("Images:", new { @class = "control-label col-md-2" })
<div class="col-md-1">
<input type="file" name="uploads" id="upload1" />
</div>
<div class="col-md-offset-2 col-md-1">
<input type="file" name="uploads" id="upload2" />
</div>
<div class="col-md-offset-2 col-md-1">
<input type="file" name="uploads" id="upload3" />
</div>
</div>
//code ommited for brevity..
Also if somebody could tell me how to change this properly I would be grateful.
I am getting first image of product as many times as many images a product got. I want to display all images once. I am in trouble with a directory to images.
<div class="row">
<label class="control-label col-md-2"> Obecne zdjęcia:</label>
@foreach (var item in Model.FilePaths)
{
<div class="col-md-offset-1 col-md-1">
<img src="~/Content/Images/@Model.FilePaths.FirstOrDefault(f => f.FileType == FileType.Photo).FileName" alt="" style="width:auto; height:100px">
</div>
}
</div>
My model class for FilePath:
public class FilePath
{
public int FilePathId { get; set; }
public string FileName { get; set; }
public FileType FileType { get; set; }
public int? ProductId { get; set; }
//navigation..
public virtual Product Product { get; set; }
}
Every help much appreciated. Thanks!