如何在没有冗余的情况下更新/编辑asp.net mvc 5中的上传文件? [英] How update/edit uploaded files in asp.net mvc 5 without redundancy?

查看:138
本文介绍了如何在没有冗余的情况下更新/编辑asp.net mvc 5中的上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Asp.net MVC 5 中使用 Razor Engine 更新数据时出现问题。
我的更新代码工作正常,但我遇到了一些问题。当我更新图像时,旧图像保留在图像文件夹中。我想删除旧图像,如果它改变了。如果没有改变,我想留下旧图像。
我该怎么办?
非常感谢任何帮助
我不知道怎么写if语句:/

I have a problem with update data in Asp.net MVC 5 with Razor Engine . my Update code works fine but I have some problems with it . When I update Image , old image stays in Images folder. I want to delete old image if it changed . and I want to stay old image if it didn't change . How can I do it ? Thanks a lot for any help I don't know how write if statement for this :/

CarouselRepositories.cs

public bool Update(NP1.Models.Carousel entity, bool autoSave = true)
    {
        try
        {

            db.Carousels.Attach(entity);
            db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
            if (autoSave)
                return Convert.ToBoolean(db.SaveChanges());
            else
                return false;
        }
        catch
        {
            return false;
        }
    }

管理控制器

[HttpGet]
    public ActionResult EditCarousel(int id)
    {

        var load = db.Carousels.Find(id);
        return View(load);
    }

    [HttpPost]
    public ActionResult EditCarousel(Carousel carousel, HttpPostedFileBase UploadImage)
    {
        CarouselRepositories blCarousel = new CarouselRepositories();
        string path = "";
        var fileName = "";
        var rondom = "";
        if (UploadImage != null)
        {

            fileName = Path.GetFileName(UploadImage.FileName);
            rondom = Guid.NewGuid() + fileName;
            path = System.IO.Path.Combine(
                                  Server.MapPath("~/Images/Carousel"), rondom);

            carousel.CarouselImage = rondom;
        }
        if (ModelState.IsValid)
        {

            UploadImage.SaveAs(path);
            carousel.CarouselImage = rondom;
            if (blCarousel.Update(carousel))
            {
                return JavaScript("alert('Carousel slide added');");
            }
            else
            {
                return JavaScript("alert('didn't add');");
            }
        }
        else
        {
            return JavaScript("alert('Error');");
        }

    }

EditCarousel.cshtml:

@model NP1.Models.Carousel

@{
ViewBag.Title = "EditCarousel";
Layout = "~/Views/Admin/AdminLayout.cshtml";
}
 @using (Html.BeginForm("EditCarousel", "Admin", FormMethod.Post, new { enctype = "multipart/form-data", id = "myUploadForm" }))
{
@Html.AntiForgeryToken()

<div class="form-horizontal">

    @Html.ValidationSummary(true)
    @Html.HiddenFor(model => model.CarouselID)
    <div class="form-group">
        @Html.LabelFor(model => model.CarouselSubject, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CarouselSubject)
            @Html.ValidationMessageFor(model => model.CarouselSubject)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CarouselInfo, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.CarouselInfo)
            @Html.ValidationMessageFor(model => model.CarouselInfo)
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.CarouselImage, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @*@Html.EditorFor(model => model.CarouselImage)*@
            @Html.ImageFor(model => model.CarouselImage, new {width="300"},"","Images","Carousel")
            @Html.Upload("UploadImage")
            @Html.HiddenFor(model => model.CarouselImage)
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Save" class="btn btn-default" />
        </div>
    </div>
</div>
}

更新Amin控制器:

 [HttpPost]
    public ActionResult EditCarousel(Carousel carousel, HttpPostedFileBase UploadImage)
    {
        CarouselRepositories blCarousel = new CarouselRepositories();
        string path = "";
        var fileName = "";
        var rondom = "";
        if (UploadImage != null)
        {

            fileName = Path.GetFileName(UploadImage.FileName);
            rondom = Guid.NewGuid() + fileName;
            path = System.IO.Path.Combine(
                                  Server.MapPath("~/Images/Carousel"), rondom);

            carousel.CarouselImage = rondom;
        }
        else
        {
            fileName = carousel.CarouselImage;
            path = System.IO.Path.Combine(
                                  Server.MapPath("~/Images/Carousel"), fileName);
        }
        if (ModelState.IsValid)
        {

            UploadImage.SaveAs(path); // I got error in this line 
            carousel.CarouselImage = rondom;
            if (blCarousel.Update(carousel))
            {
                return JavaScript("alert('Carousel slide added');");
            }
            else
            {
                return JavaScript("alert('didn't add');");
            }
        }
        else
        {
            return JavaScript("alert('Error');");
        }

    }


推荐答案

如果在POST方法中 UploadImage 的值不是 null ,则假设您要删除当前文件,然后你可以使用 System.IO.File.Delete 方法

Assuming you want to delete the current file if the value of UploadImage is not null in the POST method, then you can use the System.IO.File.Delete method

private const string _ImagesPath = "~/Images/Carousel";

[HttpPost]
public ActionResult EditCarousel(Carousel carousel, HttpPostedFileBase UploadImage)
{
  if (ModelState.IsValid)
  {
    CarouselRepositories blCarousel = new CarouselRepositories();
    if (UploadImage != null)
    {
      // Delete exiting file
      System.IO.File.Delete(Path.Combine(Server.MapPath(_ImagesPath), carousel.CarouselImage));
      // Save new file
      string fileName = Guid.NewGuid() + Path.GetFileName(UploadImage.FileName);
      string path = Path.Combine(Server.MapPath(_ImagesPath), fileName);
      UploadImage.SaveAs(path)
      carousel.CarouselImage = fileName;
    }
    if (blCarousel.Update(carousel))
    {
      ....
    }
    else
    {
      ....
    }
  }
  else
  {
    ....
  }
}

这篇关于如何在没有冗余的情况下更新/编辑asp.net mvc 5中的上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆