I have web api controller method to download excel file, by passing "FileName" as a parameter, can anybody help me how to download the file using $.Ajax or any other possible way.
API Controller method
[HttpPost]
[Route("api/POSTargets/DownloadFile")]
public HttpResponseMessage DownloadExcel(string FileName)
{
var filePath = @"~/POSTarget/" + FileName;
var path = HttpContext.Current.Server.MapPath(filePath);
if (path != null)
return FileAsAttachment(path, "Errors POS Target.xlsx");
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
public static HttpResponseMessage FileAsAttachment(string path, string filename)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
result.Content = new StreamContent(stream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = filename;
return result;
}
---View
function downloadFile() {
debugger;
var fileName= "Error POS Target372016182355.xlsx";
$.ajax({
url: "http://localhost/RPMS/api/POSTargets/DownloadFile",
type: "POST",
data: fileName
}).done(function (data) {
alert(data);
}).error(function (data) {
alert(data);
});
}