How to force download of file from ASP.NET WebAPI
asp.net, asp.net-mvc, asp.net-web-api, jquery, rest
Solution
As stated, you can't trigger 'the open/save as' dialog from ajax.
If you want to preserve the current page content while downloading the file you could add a hidden iframe somewhere in your page and have your download link do some JS behind the scenes to set the src attribute of said iframe to the appropriate location.
$('iframeSelector').attr('src', downloadLinkLocation)
I've tested this with an action returning a FileContentResult but if you set ContentDisposition in the response headers, as you do, I see no reason why it wouldn't work with the WebAPI method.
Problem
This is my web-api code: ``` [HttpPost] public HttpResponseMessage PostFileAsAttachment() { string path = "D:\\heroAccent.png"; if (File.Exists(path)) { 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 = "xx.png"; return result; } return new HttpResponseMessage(HttpStatusCode.NotFound); } ``` And how to Code the Client side(view) to force a download file to me(like auto download mode(open、save as) can pop up...)