0

I have a web api method which returns a file. the controller method is as below:

        public HttpResponseMessage Get(string id)
        {
            HttpResponseMessage result = null;
            var localFilePath = HttpContext.Current.Server.MapPath("~/" + id);

            // check if parameter is valid
            if (String.IsNullOrEmpty(id))
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
            // check if file exists on the server
            else if (!File.Exists(localFilePath))
            {
                result = Request.CreateResponse(HttpStatusCode.Gone);
            }
            else
            {// serve the file to the client
                result = Request.CreateResponse(HttpStatusCode.OK);
                result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
                result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
                result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
                result.Content.Headers.ContentDisposition.FileName = id;
            }

            return result;
        }       

I need to write a sample html which does call this api and download the file from the html page. How can i do that using $.ajax or some other way?

Regards, John

Silly John
  • 1,584
  • 2
  • 16
  • 34
  • Did you try [this](https://stackoverflow.com/questions/34586671/download-pdf-file-using-jquery-ajax)? – ibubi Jun 04 '17 at 21:49
  • That worked. Thanks!! – Silly John Jun 04 '17 at 22:22
  • You're welcome, I haven't tried this, did you ensure this working on all major browsers ? Btw please post an answer explains how you made it work for whom have similar problems. – ibubi Jun 05 '17 at 06:56

0 Answers0