How to download binary using ASP.net Web API and Javascript?

I have an API API that looks like this:

using System; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Threading.Tasks; using System.IO; namespace APIIntegration.Controllers { public class TestController : ApiController { // http://localhost/api/test [HttpGet] public async Task<HttpResponseMessage> Get() { Stream stream = streamWith256Bytes; HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK); result.Content = new StreamContent(stream); result.Content.Headers.ContentLength = stream.Length; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = "foo.bin"; return result; } private static Stream streamWith256Bytes { get { MemoryStream stream = new MemoryStream(); for (int i = 0; i <256 ; i++) { stream.WriteByte(Convert.ToByte(i)); } stream.Position = 0; return stream; } } } } 

In short, this controller is trying to load a 256-byte file into the browser. At first it works, but when the downloaded file is checked, the size is 512 bytes instead of the expected 256 bytes, and non-printable characters will be destroyed.

How can I change this code so that binary data can be loaded correctly?

Edit: It should also be mentioned that I saw a similar question here: Problems downloading the pdf file from the api web service , where the problem was fixed by adding a content length header, but this did not solve for me.

Edit: I modified the source code above to give a complete working example of how to reproduce.

Edit: I found that the above code really works correctly when I provide the address in the address bar, but when using Javascript to start the download, where I have a problem.

+5
source share
1 answer

I have found a solution. In my Javascript, I used Angular to start the file upload using the Angular $ http service. By default, this service interprets the response as text. I had to tell Angular to interpret the answer as blob, and that fixed everything.

My working code is as follows:

 function download(downloadUrl) { $http({ url: downloadUrl, responseType: "blob" }) .then(function (response) { var blob = new Blob([response.data], { type: "application/octet-stream" }); saveAs(blob, "foo.bin"); }, function (response) { alert("error downloading file from " + downloadUrl); }); } 
+4
source

Source: https://habr.com/ru/post/1235577/


All Articles