How to force download a file from ASP.NET WebAPI

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 like the code โ€œCopy clientโ€ (view) to force me to download the file (for example, the automatic download mode (open, save as) may appear ...)

+4
source share
2 answers

As indicated, you cannot start the open / save as dialog from ajax.

If you want to keep the current content of the page during file upload, you can add a hidden iframe somewhere on your page and have a download link so that some JS backstage sets the src attribute of the specified iframe to the appropriate location.

 $('iframeSelector').attr('src', downloadLinkLocation) 

I checked this with an action that returns a FileContentResult, but if you set the ContentDisposition in the response headers like you, I see no reason why it will not work with the WebAPI method.

+2
source

One of the types of ActionResult available for files is FileResult. If the content you want to transfer is stored in a disk file, you can use the FilePathResult object. If your content is accessible through a stream, you use FileStreamResult, and you select FileContentResult if you have it as a byte array. All these objects come from FileResult and differ from each other only in the way they write data to the response stream.

ex: for PDF

 public FileResult Export() { var output = new MemoryStream(); : return File(output.ToArray(), "application/pdf", "MyFile.pdf"); } 

Please find the link below to learn how to call an action method using Ajax jQuery

http://blog.bobcravens.com/2009/11/ajax-calls-to-asp-net-mvc-action-methods-using-jquery/

You can link to these articles, which could give you some insight into FileResult.

http://www.dotnetcurry.com/ShowArticle.aspx?ID=807

0
source

All Articles