使用 Ajax 从 Web api 获取二进制数组时没有从文本到数组缓冲区的转换

No conversion from text to arraybuffer when using Ajax to get binary array from web api

我正在尝试从 ajax 客户端的 Web api 接收二进制数组,

在我的 Api 控制器中我有:

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

在我的 JavaScript 我有:

function RenderImage() {
    try {

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

我收到错误:

No conversion from text to arraybuffer

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.

参考:

试试下面的代码:

控制器

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

Javascript : 使用 base64ToArrayBuffer 函数:

<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>