【问题标题】:Asp.net core I could add pictures, but I couldn't delete the imageAsp.net core 我可以添加图片,但是我不能删除图片
【发布时间】:2019-03-24 09:00:40
【问题描述】:

我正在使用 Asp.Net MVC Core。我可以添加图片,但我无法删除图片。我无法使用以下方法:Server、MapPath。

实体添加和图片上传:(成功的方法。我刚刚分享了我是如何添加的。)

  public async Task<IActionResult> Create(IFormFile image,Programci programci)
    {
        if (image==null || image.Length==0)
        {
            return Content("not image selected");
        }

        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/image/Programcilar", image.FileName);

        using (var stream = new FileStream(path, FileMode.Create))
        {
            await image.CopyToAsync(stream);

        }

        programci.ImageUrl = "/image/Programcilar/"+ image.FileName;
        _programciService.Add(programci);

        return RedirectToAction("Index");
    }

删除方法:(问题。我无法删除图像。)

 public ActionResult Delete(int id)
    {
        var bulunanProgramci = _programciService.Get(id);


        _programciService.Delete(id);
        return RedirectToAction("Index");
    }

【问题讨论】:

  • 能否提供更多_programciService.Delete(id);方法的代码?

标签: c# file asp.net-core-mvc image-uploading


【解决方案1】:

根据您的代码和图像,_programciService.Delete(id); 方法调用内的代码中应该有类似的内容

var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\image\\Programcilar", "controlller.jpg");

if(System.IO.File.Exists(path))
{
    System.IO.File.Delete(path);
}

只需将静态图像文件名"controlller.jpg" 替换为您要删除的图像的变量名即可。

注意图片的路径。它应该是根驱动器的完整路径。例如C:\\inetpub\\wwwroot\\image\\Programcilar\\controlller.jpg

【讨论】:

  • if (System.IO.File.Exists(_env.WebRootPath+bulunanProgramci.ImageUrl)) { System.IO.File.Delete(_env.WebRootPath + bulunanProgramci.ImageUrl); } 谢谢 :)
【解决方案2】:

我建议使用环境变量来存储/检索您存储图像的路径。

string uploadsFolder = Path.Combine(webHostEnvironment.WebRootPath, "Images");
        var path = System.IO.Path.Combine(Directory.GetCurrentDirectory(), uploadsFolder, picName);

        if (System.IO.File.Exists(path))
        {
            System.IO.File.Delete(path);
        }

别忘了使用:

private readonly IWebHostEnvironment webHostEnvironment;

并在你的类的构造函数中实例化它:

public yourClass(yourContext context, IWebHostEnvironment hostEnvironment)
    {
        _context = context;
        webHostEnvironment = hostEnvironment;
    }

【讨论】:

    猜你喜欢
    • 2019-05-09
    • 1970-01-01
    • 2015-03-22
    • 2014-07-10
    • 1970-01-01
    • 2018-06-16
    • 2018-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多