简体   繁体   中英

Deleting files from wwwroot folder, what I am doing wrong?

With my controller I am able to upload files to certain path. I am trying to figure out how to delete iterated file in my view.

Controllers method:

[Authorize(Roles = "Moderatorzy")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteFile(string file)
        {
            if (!System.IO.File.Exists(file))
            {
                return NotFound();
            }
            System.IO.File.Delete(file);
            return View("Edit");
        }

View file:

<form asp-action="Edit" method="post" enctype="multipart/form-data">
        <input type="hidden" asp-for="ID" />
        (...)
        @if (Enumerable.Count(ViewBag.fileList) != 0)
        {
            <dir>Files to download:</dir>
            {
                foreach (var file in ViewBag.fileList)
                {
                    <a class="down" href="Autobus/DeleteFile?file=@(ViewBag.fileDirectory + file)"><dir>@file<span>;</span></dir></a>

                }
            }
        }
(...)
        <div class="text-center">
            <button class="btn btn-success" type="submit">Zapisz</button>
            <a href="javascript:history.go(-1)" class="btn btn-primary">Powrót</a>
        </div>
<div class="space"></div>

Right now I am having 2 issues:

1) Autobus is the controller name. href="Autobus/DeleteFile?file=@(ViewBag.fileDirectory + file)" gives me path: /Autobus/Autobus/DeleteFile(...) instead of /Autobus/DeleteFile(...) . Why?

2) After typig manually just one Autobus it does not call DeleteFile method. Why?

Complete generated route path is: http://localhost:50686/Autobus/Autobus/DeleteFile?file=C:\\Users\\asus\\Desktop\\Praca%20IT\\Programowanie\\Projekty\\DluzynaSzkola\\ASP.NET%20Core%20-%20ostatni\\Dluzyna_Szkola_2\\BasicConfig\\wwwroot/uploaded/bus/1.jpg

PS I am guessing it might be something wrong with routing.

This part of your complete generated path:

C:\\Users\\asus\\Desktop\\Praca%20IT\\Programowanie\\Projekty\\DluzynaSzkola\\ASP.NET%20Core%20-%20ostatni\\Dluzyna_Szkola_2\\BasicConfig\\wwwroot/uploaded/bus/1.jpg

is because of ViewBag.fileDirectory in this line of code ->

<a class="down" href="Autobus/DeleteFile?file=@(ViewBag.fileDirectory + file)"><dir>@file<span>;</span></dir></a>

You use your real path of the file in your server (local computer) for your view and this can make a lot of problems. You should define something like id for each file and then send id of that file to your controller action method and after that then realize this id is for which file and finally delete that file.

So you must change your code like this:

In this situation the name of your file is id. Although this is not the standard way. We do this just for learning purpose.

Change this line of your code ->

<a class="down" href="Autobus/DeleteFile?file=@(ViewBag.fileDirectory + file)"><dir>@file<span>;</span></dir></a> 

With this line ->

@Html.ActionLink( $"Delete {file}", "DeleteFile", "Autobus", new { file = file}, new { })

Now when you click on each of generated links in your browser, your action method DeleteFile will receive the file name. and then if you know which directory are your files, you can delete it in your DeleteFile action method with one line of code like this

System.IO.File.Delete(fileDirectory+file);

Notice: If your fileDirectory path is something like this C:\\Users\\asus\\Desktop\\Praca%20IT\\Programowanie\\Projekty\\DluzynaSzkola\\ASP.NET%20Core%20-%20ostatni\\Dluzyna_Szkola_2\\BasicConfig\\wwwroot/uploaded/bus/1.jpg your action mehtod ( DeleteFile ) will throw an exception. So you must change your code in this way:

string fullPath = Request.MapPath("~/uploaded/" + file);
if (System.IO.File.Exists(fullPath))
{
   System.IO.File.Delete(fullPath);
}

In this code ~ specify root of your asp.net MVC application and uploaded folder is a folder that you use for locating your files (you can change it to your files folder).

If you change your code in this way you may have some little problems at first but the concept is right and with a little change you can do what you want.

I Hope This Answer Can Help You....

My final working solution:

View file:

(...)
@if (Enumerable.Count(ViewBag.fileList) > 0)
    {
        <dir>Wgrane już pliki:</dir>
        {
            foreach (var someFile in ViewBag.fileList)
            {
                <form asp-action="DeleteFile" method="post">
                    @Html.AntiForgeryToken()
                    <input type="hidden" name="file"value="@someFile" asp-action="@(ViewBag.fileDirectory + someFile)" />
                    <button class="btn btn-danger" type="submit">Usuń</button>
                    @someFile
                </form>
            }
        }
    }
(...)

Also in my DeleteFile method I had to add ViewBags:

[Authorize(Roles = "Moderatorzy")]
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteFile(string file)
        {
            string fileDirectory = Path.Combine(
                      Directory.GetCurrentDirectory(), "wwwroot/uploaded/bus/");
            ViewBag.fileList = Directory
                .EnumerateFiles(fileDirectory, "*", SearchOption.AllDirectories)
                .Select(Path.GetFileName);
            ViewBag.fileDirectory = fileDirectory;
            string webRootPath = _hostingEnvironment.WebRootPath;
            var fileName = "";
            fileName = file;
            var fullPath = webRootPath + "/uploaded/bus/" + file;

            if (System.IO.File.Exists(fullPath))
            {
                System.IO.File.Delete(fullPath);
                ViewBag.deleteSuccess = "true";
            }
            return View("Edit");
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM