5

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 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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");

1 Comment

I know...I tried text/plain, text/txt and others, and still got nothing!
0

Check mime extension in web.config / IIS

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.