xmorera
xmorera

Reputation: 1961

Download file using Javascript from a bytearray

I have a button in my asp net app that when pressed I am calling a rest service that returns a bytearray.

This bytearray is actually a file that I need to start downloading in the browser when the button is pressed. How can I achieve this?

I am thinking along the lines of writing the bytearray to the response and setting the headers.

Is this thinking correct and does someone have some code samples?

---------Update on 3/25---------------- Thanks Justin but not yet what I need. Please look at this link it will return a file for download. What I need to do is have an event client side that will get this file for download without redirecting to this page. It has to be downloaded from my page and not this link.

http://ops.epo.org/3.0/rest-services/published-data/images/US/5000001/PA/firstpage.pdf?Range=1

If you check it out with Fiddler, you will see how the pdf is received as binary.

Upvotes: 1

Views: 4293

Answers (2)

Justin Thomas
Justin Thomas

Reputation: 5848

You can set the responseType as arraybuffer and access it that way. There is even a way to stream the data using onprogress events. JavaScript has come a long way.

var oReq = new XMLHttpRequest();
oReq.open("GET", "/myfile.png", true);
oReq.responseType = "arraybuffer";

oReq.onload = function (oEvent) {
  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  if (arrayBuffer) {
    var byteArray = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteArray.byteLength; i++) {
      // do something with each byte in the array
    }
  }
};

oReq.send(null);

https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest/Sending_and_Receiving_Binary_Data

If you mean that the webservice isn't returning binary data, and instead is JSON data like: [0,1,3,4] then that is a different issue.

Upvotes: 1

Evan Mosseri
Evan Mosseri

Reputation: 394

As far as i know, the closest thing you can do with javascript is an ajax request that has the server parse the data as text

Upvotes: 0

Related Questions