How to download a file using JQuery code from web api

Create a web api controller like below.

using System;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Description;
using AdeptAccelerator.Application.Services.XML;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Configuration;
using AdeptAccelerator.API.Common;

namespace AdeptAccelerator.API.v1.Controllers.Domain.XML
{
    [RoutePrefix("api/domain/XML")]
    public class XMLController : BaseController
    {

        [HttpGet, Route("DownLoadXML")]
        [ResponseType(typeof(HttpResponseMessage))]
        public HttpResponseMessage DownLoadXML()
        {
            return DownloadXMLFile();
        }
    }

Create a method for getting xml file from local folder

public HttpResponseMessage DownloadXMLFile(string filename)
      {
     
          var fileinfo = new FileInfo(filename);
          if (!fileinfo.Exists)
          {
              throw new FileNotFoundException(fileinfo.Name);
          }
          try
          {
              HttpResponseMessage response = new HttpResponseMessage();
              response.Content = new StreamContent(File.OpenRead(filename));
              response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/xml");
              response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
              {
                  FileName = "test.xml",
              };
              return response;
          }
          catch (Exception ex)
          {
              throw ex;
          }

      }

}
Now add below anchor tag into html.

<a  id = "btnDownloadXML"class="btn btn-info" href="#"><span>Download XML</span></a>

Copy and paste below JavaScript code to JavaScript file

$(document).on("click", "#btnDownloadXML", function () {
     jQuery.support.cors = true;  // This is for cross domain 
   var  url = apiDomain + "XML/DownLoadXML;
   var hiddenElement = document.createElement('a');
    hiddenElement.href = url;
    hiddenElement.download = 'test';
    hiddenElement.target = '_blank';
    hiddenElement.click();
    });


How to change xml file inner text or attribute value using c#.

   private XmlDocument ChangeXMLDoc(string filepath)

       {
           XmlDocument document = new XmlDocument();
            document.Load(filepath);
           XmlNodeList nodeList;
           nodeList  = document.GetElementsByTagName("PlanId");
     foreach (XmlNode xnode in nodeList)
          {
                 xnode.InnerText = "Hello world";  // This is for innertext value change 
           xnode.Attributes["code"].Value = "Hello world"; // This is for attribute value change.
          }
         

           return document;

}

No comments:

Post a Comment