2

The uploading images API needs binary stream. I've tried new FileReader() and its readAsBinaryString() method, but it doesn't work! It seems that binary string and binary stream are not the same thing, so I changed my way and tried readAsDataURL() method (cause I need to preview images) and now I want to know:

1) how to convert base64 into binary stream using js?

When I use readAsBinaryString(),the respond is as follow (data A):

binary_string

But the API needs something like this (data B):

binary_stream

2) Anybody know how to convert dataA ( picture above ) into dataB ( picture down )?

lokusking
  • 7,396
  • 13
  • 38
  • 57
Steven Zhang
  • 21
  • 1
  • 1
  • 4
  • 1
    _"I've tried new FileReader() and its *readAsBinaryString()*method, but it doesn't work!"_ What do you mean by "binary stream"? – guest271314 Sep 19 '16 at 06:26
  • when you say "it doesn't work" - do you get errors in the console for example? – Jaromanda X Sep 19 '16 at 06:26
  • I'm having a hard time believing the api need a hex view `(data B)` when you say that the api needs a binary stream - which one is it? – Endless Nov 10 '16 at 15:19

1 Answers1

9

This is how you convert a base64 into binary stream

var base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

fetch(base64)
.then(res => {
  console.log(res.body instanceof ReadableStream)
})
Note: This only works in Blink atm, could use Screw-FileReader and web-streams-polyfill to turn any blob into a byte stream if you like

But what i really think you wanna do is to turn a base64 into a blob (binary container) and then upload it to a api as binary (not as base64) if that is true then this is just a duplicate of Creating a Blob from a base64 string in JavaScript and then it's just a mather of sending it with ajax to a server

var base64 = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

fetch(base64)
.then(res => res.blob())
.then(blob => {
  console.log("here is your binary: ", blob)

  // now upload it
  fetch(api, {method: 'POST', body: blob})
})

Getting the base64 in the first place is really impractical and should be dealt with before using arrayBuffer, or blob
If you for example getting it from canvas - try using canvas.toBlob instead of toDataUrl

Community
  • 1
  • 1
Endless
  • 34,080
  • 13
  • 108
  • 131
  • i am working on React Native App, fetch method is working fine for ios but not working for android! is there anything alternative to convert base64 into blob? – Shawal Ahmad Khan Jul 20 '22 at 17:59