且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有冗余的情况下更新/编辑asp.net mvc 5中的上传文件?

更新时间:2022-11-03 14:16:41

如果在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
  {
    ....
  }
}