0

I am trying to receive binary array from web api from ajax client,

In my Api Controller I have:

[ HttpGet ]
[ Route( "Connection/ImageData" ) ]
public byte[] GetImageData()
{
    return new byte[1];
}

In my JavaScript I have:

function RenderImage() {
    try {

        $.ajax({
            url: "/Connection/ImageData",
            dataType: "arraybuffer",
            success: function(response) {                  
               //success!
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
               //api error;
            }
        });
    } catch (err) {
        //calling error
    }
}

I get the error:

No conversion from text to arraybuffer
Andrew Simpson
  • 6,883
  • 11
  • 79
  • 179

1 Answers1

2

The returned byte array will be converted into text in some way, depending on how the MediaTypeFormatterCollection is set up on the server and on the format requested by the HTTP client with the Accept header. The bytes will typically be converted to text by base64-encoding. The response may also be packaged further into JSON or XML, but the ratio of the expected length (528) to the actual length (706) seems to indicate a simple base64 string.

Reference :https://stackoverflow.com/a/23884624/10201850

Try the following code :

Controller

    [HttpGet]
    [Route("Connection/ImageData")]
    public string GetImageData()
    {
        var bytes = new byte[3] { 0,12,246 };
        var data = Convert.ToBase64String(bytes);
        return data;
    }

Javascript : using base64ToArrayBuffer function:

<script type="text/javascript">

    function base64ToArrayBuffer(base64) {
        var binaryString = window.atob(base64);
        var binaryLen = binaryString.length;
        var bytes = new Uint8Array(binaryLen);
        for (var i = 0; i < binaryLen; i++) {
            var ascii = binaryString.charCodeAt(i);
            bytes[i] = ascii;
        }
        return bytes;
    }
    $("#btnclick").click(function () {
        try {
            $.ajax({
                url: "/Connection/ImageData",
                //dataType: "arraybuffer",
                success: function (response) {
                   var result= base64ToArrayBuffer(response);
                    console.log(result);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    console.log(errorThrown);
                    //api error;
                }
            });
        } catch (err) {
            //calling error
        }

    });
</script>
Xueli Chen
  • 11,987
  • 3
  • 25
  • 36
  • Thanks, but I do want to actually return a byte array without converting it to base64. I know you can do this using websockets. But usefulful code so +1. – Andrew Simpson Aug 08 '19 at 11:40