简体   繁体   English

从文件夹中删除文件-Ajax ASP.NET C#

[英]Delete file from folder - ajax asp.net c#

I am trying to delete file from folder using ajax and Handler.ashx . 我正在尝试使用ajax和Handler.ashx从文件夹中删除文件。 I have a link when clicked calls removefile() method which further calls method in handler.ashx to delete file. 单击时,我有一个链接调用removefile()方法,该方法进一步调用handler.ashx中的方法以删除文件。 But it is not working. 但这是行不通的。 The result returned on success in ajax is always empty and file is not deleted. 在ajax中成功返回的结果始终为空,并且不会删除文件。

Below is the code: 下面是代码:

function removeFile(fileName)
        {
            $.ajax({
                 url: 'Handler.ashx/deleteFile',
                type: 'POST',
                data: { 'sFileName': fileName},
                contentType: false,
                processData: false,
                success: function (result) {
                    debugger;
                    alert(result);
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(xhr.responseText);
                    alert(thrownError);
                }
            });

        }

Below shows the code in Handler.ashx: 下面显示了Handler.ashx中的代码:

public void deleteFile(HttpContext context) {
        string sFileName = context.Request["sFileName"];
        if (File.Exists(context.Server.MapPath("~/Files/" + sFileName)))
        {
            File.Delete(context.Server.MapPath("~/Files/" + sFileName));
            context.Response.ContentType = "text/plain";
            context.Response.Write("File Removed Successfully!");
        }
        else
        {
            context.Response.ContentType = "text/plain";
            context.Response.Write("File Removed Failed!");
        }
    }

Please guide me what am I doing wrong. 请指导我我在做什么错。 Thank you in advance 先感谢您

ashx-Handlers aren't called like mvc controllers: there is no mechanism mapping your url onto a method name, so I don't think your deleteFile-method is called at all. ashx-Handlers不像mvc控制器那样被调用:没有将您的url映射到方法名称的机制,因此我认为根本不会调用您的deleteFile方法。 You can verify this by setting a breakpoint. 您可以通过设置断点来验证这一点。

You should implement a ProcessRequest-method. 您应该实现一个ProcessRequest方法。 In this method, you can verify the full url and call your DeleteFile-method (please start .net method names with a capital) with the correct parameters. 在此方法中,您可以验证完整的URL并使用正确的参数调用DeleteFile方法(请以大写字母开头的.net方法名称)。

A full explanation on using handlers can be found here: https://www.dotnetperls.com/ashx 可以在以下位置找到有关使用处理程序的完整说明: https : //www.dotnetperls.com/ashx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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