william
william

Reputation: 13

Download a byte array in binary format

I'm working on this code where I want to download a byte array, and its working at this point, but the downloaded file is encoded in ascii.

The downloaded file shows "65,66,67,0,0,0,0,0,0,0"

but I was expecting "ABC"

How can I change this code to get this file in binary format?

<!DOCTYPE html>
<html>

<body>

<h1>Writing a binary file</h1>

<script>
    
  var dados = new Int8Array(10);

  dados[0]=65;
  dados[1]=66;
  dados[2]=67;
  
  function download()
  {
    let element = document.createElement('a');
    element.setAttribute('href', 'data:application/octet-stream,' + dados );
    element.setAttribute('download', "teste.bin" );
    element.style.display = 'none';
    document.body.appendChild(element);
    element.click();
    document.body.removeChild(element);
  }
  download();


</script>

</body>
</html>

Upvotes: 1

Views: 1345

Answers (1)

paulsm4
paulsm4

Reputation: 121881

I see what's happening. You're inadvertently converting Int8Array "dados" into a text string. Whoops!

Here's an alternative approach:

<!DOCTYPE html>
<html>
<body>

<h1>Writing a binary file</h1>

<script>  
  function download(bytes, fname)  {
    debugger;
    let blob = new Blob([bytes], {type:"application/octet-stream"});
    let link = document.createElement('a');
    link.href = window.URL.createObjectURL(blob);
    link.download = fname;
    link.click();
  }

  let dados = new Int8Array(10);
  dados[0]=65;
  dados[1]=66;
  dados[2]=67;

  download(dados, "teste.bin"); 
</script>

</body>
</html>

I would also consider terrymorse's excellent suggestion about using fetch().

Upvotes: 1

Related Questions