Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Web API downloading text

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:

  • Is there a way to force ASP.NET Web API to return plain text?

  • Returning binary file from controller in ASP.NET Web API

  • ASP .Net Web API downloading images as binary

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"..

like image 569
Izzy Rodriguez Avatar asked Oct 06 '22 20:10

Izzy Rodriguez


1 Answers

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

like image 185
Izzy Rodriguez Avatar answered Oct 24 '22 05:10

Izzy Rodriguez