Pankaj Upadhyay
Pankaj Upadhyay

Reputation: 13594

Unable to delete file via jquery to MVC action

I am invoking a action method via jquery and trying to delete a file. But nothing happens. The file still exist.

Following is jquery Code

$("#pictureRemove").click(function (e) {
            $("#pictureImage").html("<img src='../../Content/Images/noDefaultImage_100.gif'/>");
            $(this).hide();
            $.ajax({
                type: 'POST',
                url: '@Url.Action("Remove", "Category")',
                data: { fileName: $('#pictureTitle').attr('src') },
                dataType: 'json'
                    // User your JSON response.
            });
        });

Following is the action method code

    [HttpPost]
    public ActionResult Remove(string fileName)
    {
        string completFileName = Server.MapPath("~/Content/Images/" + fileName);
        System.IO.File.Delete(completFileName);
        return Json(true);
    }

Upvotes: 2

Views: 1437

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039160

On this line:

data: { fileName: $('#pictureTitle').attr('src') }

you seem to be passing the fileName parameter to the controller action from the src parameter of some image. So I suppose that you have some image like this:

<img id="pictureTitle" src="/Content/images/foo.jpg" />

so you are passing /Content/images/foo.jpg so in your controller action you are trying to delete Server.MapPath("~/Content/Images//Content/images/foo.jpg") which is translated to c:\wwwroot\Content\Images\Content\images\foo.jpg which is unlikely to exist and an exception is thrown.

Simply put a breakpoint in your controller action and inspect the different parameters.

This being said exposing a controller action that takes a filename and deletes the file on the server is a huge security hole in your application.

Upvotes: 6

Related Questions