Tuesday, 28 May 2013

File Delete using jQuery in ASP.NET

In the page body add 
<script language="javascript" type="text/javascript" src="jquery_bundle/jquery-1.9.1.js"></script>
<input id="Button1" type="button" value="delete" runat="server" onclick="deleteFile();" />
<script language="javascript" type="text/javascript">
    function deleteFile() {
        var fileName = "1st.jpg";
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "WebService.asmx/deleteFile",
            data: "{'fileName':'" + fileName + "'}",
            dataType: "json",
            async: true,
            success: function(data) {
            alert(data.d);
            },
            error: function(result) {
                alert("Error");
            }
        });
    }
</script>
Add a webservice
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Web.Script.Serialization;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]

public class WebService : System.Web.Services.WebService
{
    public WebService()
    {
    }
   [WebMethod]
    public IList<string> deleteFile(string fileName)
    {
        IList<string> result = new List<string>();
        try
        {
            string completePath = Server.MapPath("~/upload/" + fileName);
            if (System.IO.File.Exists(completePath))
            {
                System.IO.File.Delete(completePath);
            }
            result.Add("Y");
            return result;
        }
        catch
        {
            return null;
        }
    }
}

No comments:

Post a Comment

Get all non-clustered indexes

DECLARE cIX CURSOR FOR     SELECT OBJECT_NAME(SI.Object_ID), SI.Object_ID, SI.Name, SI.Index_ID         FROM Sys.Indexes SI             ...