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