GridFS Binary to URL - javascript

Is there a way to convert GridFS binary to a URL that can be used on a src?
Let me explain:
When an image is stored on mongoDB by GridFS it creates to files(fs.files & fs.chunks).
In fs.chunks the data is stored like so:
_id:ObjectID('')
files_id:ObjectID('')
n:0
data:Binary('/9j/4S...',0)
Exist any way to convert that binary which is an image(a jpg to be precise) into a URL valid for a HTML img tag?
Some kind of URL.createObjectURL()
By the way, I tried to pass the binary file into URL.createObjectURL() and the displayed error is the following:
TypeError: URL.createObjectURL: Argument 1 is not valid for any of the 1-argument overloads.
Thanks in advance.

Ok, I finally find a helpful answer to my question on this other question:
Creating a BLOB from a Base64 string in JavaScript
Here, the GridFS binary which is a base64 binary is converted in to a Blob object. Then the Blob object can be easily passed through the "URL.createObjectURL()"
The function to convert the base64 to blob is provided in the answer.
I hope this is helpfull for someone else.

Related

What is the logic for sending the base64 string into image?

I have generated a Base64 string, which I have shared as an image using Capacitor FileSharer,
for this I have used two approaches-
img.split(',')[1],
This I have understood as how it is giving me the image file from removing the "data:image" from the string.
img.replace(/^data:image\/[a-z]+;base64,/, "")
This I haven't understood properly as what functions it is performing to the string that I am getting a image file. Anyone If possible, do provide an explanation.
Though I have used both of them, and both works fine. It is only I am asking because ,If I am using any property in my project , I should now how it is actually working.
(PS- I am new to Javascript )
Introduction of Base64 encoding
In computer science, Base64 is a group of binary-to-text encoding schemes that represent binary data in an ASCII string format by translating it into a radix-64 representation. The term Base64 originates from a specific MIME content transfer encoding. Each Base64 digit represents exactly 6 bits of data. Three 8-bit bytes (i.e., a total of 24 bits) can therefore be represented by four 6-bit Base64 digits (you can read more here).
Where can we use Base64 encoding on images specifically?
Basically, there are multiple advantages in using base64 images or even files such as pdf, csv, etc., in web interactions:
For storying them easily in databases as string and retrieve them accordingly.
In JSON or XML based web architectures (such as REST or SOAP) usually is hard to send images along side with form data. For example, sending profile picture along side with user form data such as username, password, first name, last name, etc., in JSON format.
Security! Anyone who does not know anything about base64 encoding cannot open files easily as it should be.

Storing Blob as int16 instead of int8 JS

I'm actually storing data obtained via MediaRecorder from an audio stream into a Blob which, after being read by FileReader.readAsArrayBuffer(), is represented as a Int8Array. Is there any way to read it as an Int16Array instead?
The recording method has been extrated from here
Thanks in advance.
After being read by FileReader.readAsArrayBuffer(), is represented as a Int8Array
No, it's a buffer.
Is there any way to read it as an Int16Array instead?
No, but you can trivially construct any typed array "view" that you need on that buffer:
new Int16Array(fileReader.result)

Word Add-in replace current document bytes

I am sending the document as byte array to an API that modifies the file and gets me a new file as a byte array.
Is it possible to replace document that I am working with currently, with the document received from the API?
If you can convert the byte array to a base64 string, then you can use the Body.insertFileFromBase64 method (with the Replace option) to do what you want. There are lots of StackOverflow answers about converting byte arrays to base64 string. For more about the Body.insertFileFromBase64 method, see Body.

Node.js node-mysql2 insert Buffer as Blob directly

What is the correct way to insert Buffer as BLOB just 1-to-1 without serializing to string/hex? Is it possible at all from Node.js?
At my backend I already have Buffers with binary data and want to store them with minimum overheads using prepared statements. I'm getting ER_TRUNCATED_WRONG_VALUE_FOR_FIELD errno:1366 Incorrect string value error. It looks like the library just assumes there is a valid utf8 string in a buffer.

What is the difference between an ArrayBuffer and a Blob?

I'm reading http://www.html5rocks.com/en/tutorials/file/xhr2/ and trying to figure out the difference between an ArrayBuffer and a Blob.
Aren't both containers comprised of bits? Hence, couldn't both containers be viewed in many ways (as 32-bit chunks, 16-bit chunks, etc.)?
Summary
Unless you need the ability to write/edit (using an ArrayBuffer), then Blob format is probably best.
Detail
I came to this question from a different html5rocks page., and I found #Bart van Heukelom's comments to be helpful, so I wanted to elevate them to an answer here.
I also found helpful resources specific to ArrayBuffer and Blob objects. In summary: despite the emphasis on Blob being immutable/"raw data" Blob objects are easy to work with.
Resources that compare / contrast ArrayBuffer vs Blob:
Mutability
an ArrayBuffer can be changed (e.g. with a DataView)
a Blob is immutable
Source / Availability in Memory
Quoting Bart van Heukelom:
An ArrayBuffer is in the memory, available for manipulation.
A Blob can be on disk, in cache memory, and other places not readily available
Access Layer
ArrayBuffer will require some access layer like typed arrays
Blob can be passed directly into other functions like window.URL.createObjectURL, as seen in the example from OP's URL.
However, as Mörre points out you may still need File-related interfaces and API's like FileReader to work with a Blob.
Convert / Generate
You can generate Blob from ArrayBuffer and vice versa, which addresses the OP's "Aren't both containers comprised of bits?"
ArrayBuffer can be generated from a Blob using the FileReader's readAsArrayBuffer method , or the async method const arrayBuffer = await blob.arrayBuffer() (thanks to #Darren G)
Blob can be generated from an ArrayBuffer as #user3405291 points out new Blob([new Uint8Array(data)]);, shown in
this answer
Use in Other Libraries
jsZip; (new JSZip()).loadAsync(...) accepts both ArrayBuffer and Blob: String/Array of bytes/ArrayBuffer/Uint8Array/Buffer/Blob/Promise
How does protocol handle ArrayBuffer vs Blob
Websocket (aka WS / WSS)
Use the webSocket's binaryType property (could have values "arraybuffer" or "blob") to "control the type of binary data being received over the WebSocket connection."
XmlHttpRequest (aka XHR)
Use the xhr's responseType property to "to change the expected response type from the server" (valid values include "arraybuffer", "blob", and others like "document", "json", and "text")
the response property will contain the entity body according to responseType, as an ArrayBuffer, Blob, Document, JSON, or string.
Other helpful documentation:
ArrayBuffer
The ArrayBuffer object is used to represent a generic, fixed-length
raw binary data buffer. You cannot directly manipulate the contents of
an ArrayBuffer; instead, you create one of the typed array objects or
a DataView object which represents the buffer in a specific format,
and use that to read and write the contents of the buffer.
Blob
A Blob object represents a file-like object of immutable, raw data.
Blob represent data that isn't necessarily in a JavaScript-native
format. The File interface is based on Blob, inheriting blob
functionality and expanding it to support files on the user's system.
It's explained on the page.
ArrayBuffer
An ArrayBuffer is a generic fixed-length container for binary data. They are super handy if you need a generalized buffer of raw data, but the real power behind these guys is that you can create "views" of the underlying data using JavaScript typed arrays. In fact, multiple views can be created from a single ArrayBuffer source. For example, you could create an 8-bit integer array that shares the same ArrayBuffer as an existing 32-bit integer array from the same data. The underlying data remains the same, we just create different representations of it.
BLOB
If you want to work directly with a Blob and/or don't need to manipulate any of the file's bytes, use xhr.responseType='blob':
If you are dealing with something that is more similar to an immutable file that may be retrieved, stored, or served as a file over HTTP, a Blob has a useful feature: blob.type (Web API docs, Nodejs docs). This returns a MIME type (such as image/png) that you can you use for your Content-Type HTTP header when serving the blob.

Categories