4

You need to get a jpg and convert to arrayBuffer, does anyone have any idea how to do this? I tried doing using a function below but without success for a Microsoft API

 document.querySelector('#inputImage').addEventListener('change', function() {

    var reader = new FileReader();
    reader.onload = function() {

      var arrayBuffer = this.result,
      array = new Uint8Array(arrayBuffer);


    };

4 Answers 4

5

You can use this function to convert your base64 Image to an Array Buffer

export async function base64ToFile(dataURL, fileName) {
    const arr = dataURL.split(',');
    const mime = arr[0].match(/:(.*?);/)[1];
    return (fetch(dataURL)
        .then(function (result) {
            return result.arrayBuffer();
        }));
}
Sign up to request clarification or add additional context in comments.

1 Comment

fetch to get a Response from a base64 string! That's super smart! Thanks! I'm stealing your technique 😄
3

document.querySelector('#inputImage').addEventListener('change', function() {

    var reader = new FileReader();
    reader.onload = function() {

      var arrayBuffer = new Uint8Array(reader.result);
        console.log(arrayBuffer);
      };
     reader.readAsArrayBuffer(this.files[0]);  
 });
<input type="file" id="inputImage">

1 Comment

From Review: Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. Please edit your answer to explain what this code does and how it answers the question, so that it is useful to the OP as well as other users also with similar issues. See: How do I write a good answer?. Thanks
2

For the modern browsers just use the arrayBuffer method of the File object which is inherited from the Blob object:

const ab = await input.files[0].arrayBuffer();

const input = document.createElement("input");
input.type = "file";
document.body.append(input);
input.addEventListener("change", async event => {
    const ab = await input.files[0].arrayBuffer();
    const ui8a = new Uint8Array(ab);
    console.log("Uint8Array", ui8a);
});

Comments

0

Looks to me that this is something else in your code. Either use bind() :

reader.onload = function() { .... }.bind(this);

or use a fat arrow syntax:

reader.onload = () => { .... };

Because this.result if result is the property/attribute of input then i would say that this does not refers to the input element.

1 Comment

return error ReferenceError: arrayBuffer is not defined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.