5
votes

I have a WebAPI controller that need to download some files depending of the request, but when it comes to plain text files it doesnt give me the browser's download requisition. It only give me the plain text response like it was JSON (in my case, it's a JSONP WebAPI).

I've checked others Q&A from stack (and other sites), but I still got nothing:

Here it goes my current code:

var httpResponse = new HttpResponseMessage(HttpStatusCode.OK);
httpResponse.Content = new StreamContent(new MemoryStream(Encoding.UTF8.GetBytes(content)));
httpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
httpResponse.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponse.Content.Headers.ContentDisposition.FileName = "speedcam.txt";
return httpResponse;

And this is Chrome's response:

Cache-Control:no-cache

Content-Disposition:attachment; filename=speedcam.txt

Content-Length:17462

Content-Type:application/octet-stream

Date:Mon, 27 Aug 2012 04:53:23 GMT

Expires:-1

Pragma:no-cache

Server:Microsoft-IIS/8.0

X-AspNet-Version:4.0.30319

X-Powered-By:ASP.NET

X-SourceFiles:=?UTF-8?B?TTpcVHJhYmFsaG9cTWFwYVJhZGFyXE1hcGFSYWRhci5XZWJBUEk0XEV4cG9ydGE=?

Seems OK, but the whole file text is in the Chrome Dev Tools "Response Tab"..

3

3 Answers

4
votes

After a lot of research and text, I found out the hard way that an AJAX request CANNOT download files. Thanks to these two answers:

JavaScript/jQuery to download file via POST with JSON data

Ajax File Download using Jquery, PHP

0
votes

Your code is forcing the file to behave as an application, regardless of the text content;

httpResponse.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
0
votes

Check mime extension in web.config / IIS