Luiz Fernando Sousa Camargo Luiz Fernando Sousa Camargo -4 years ago 116
Ajax Question

AJAX convert image into ByteArray

I need to create a method to convert a image with AJAX to a ByteArray and send via AJAX to My API PHP.

Someone can help me?!

Thanks

Answer Source

Solution 1:

This is the sample code which is returning Bytes

Javascript :

  <script type="text/javascript">
    $(document).ready(function () {
        $('#cmdUpload').click(function () {
            uploadFile();
        });

    });

    function uploadFile() {
        var input = document.getElementById('objFile');
        // var file = $("#objFile")[0].files[0];
        var file = input.files[0];
        fr = new FileReader();
        fr.onload = receivedText;
        //fr.readAsText(file);
        fr.readAsDataURL(file);
    }

    function receivedText() {
        var b64Data = fr.result.split(',');
        var contentType = 'image/jpeg';
        //document.getElementById('editor').appendChild(document.createTextNode(fr.result))
        var byteCharacters = atob(b64Data[1]);
        var byteNumbers = Array.prototype.map.call(byteCharacters,
                                       charCodeFromCharacter);
        var uint8Data = new Uint8Array(byteNumbers);
        var blob = b64toBlob(b64Data[1], contentType);
        var blobUrl = URL.createObjectURL(blob);
    }

    function charCodeFromCharacter(c) {
         return c.charCodeAt(0);
    }

    function b64toBlob(b64Data, contentType, sliceSize) {
        contentType = contentType || '';
        sliceSize = sliceSize || 1024;
       var byteCharacters = atob(b64Data);
        var byteArrays = [];

        for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);
            var byteNumbers = Array.prototype.map.call(slice, charCodeFromCharacter);
            var byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
        }
        for (var i = 0; i < byteArray.length; i++) {
            alert(byteArray[i]);
        }

    }
</script>

HTML :

 <div>
    <input type="file" id="objFile" size="50" /><br />
    <br />
    <input type="button" id="cmdUpload" value="Upload" />
    <div id="editor"></div>
</div>

Note: require Jquery library.

Hope it will help you.

Solution 2:

Reference link:

http://www.macaalay.com/2014/09/26/rendering-images-from-byte-arrays-and-converting-images-to-byte-arrays-using-angularjs/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download