2

我有一些类似于以下的代码来下载二进制文件。我的目标是将其转换为 base64 数据 URI,同时支持可能不了解 ArrayBuffer 的旧浏览器。现在,代码似乎运行良好。

function download (url) {
    'use strict';
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'arraybuffer';
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
            var mime = xhr.getResponseHeader('Content-Type');
            var base64;
            if (oldIE) {
                var rawBytes = ieConvert(xhr.responseBody);
                base64 = encodeString64(rawBytes);
            } else if (xhr.response instanceof ArrayBuffer) {
                var payload = new Uint8Array(xhr.response);
                for (var i = 0, buffer = ''; i < payload.length; i++) {
                    buffer += String.fromCharCode(payload[i]);
                }
                base64 = window.btoa(buffer);
            } else if (xhr.response instanceof String) {
                base64 = encodeString64(xhr.response);
            }
            return 'data:' + mime + ';base64,' + base64;
        } else if (xhr.readyState === 4) {
            throw "Failed.";
        }
    };
    xhr.send();
}

我的问题是,当我使用 Google Closure Compiler 时,会收到类型警告。显然,这是因为我使用了instanceof String,但instanceof string由于对象名称应该大写,所以不起作用。

WARNING - actual parameter 1 of encodeString64 does not match formal parameter
found   : String
required: string
                    base64 = encodeString64(xhr.response);
                                            ^
0 error(s), 1 warning(s), 85.22012578616352 typed

知道如何摆脱这个警告吗?

4

1 回答 1

2
base64 = encodeString64(String(xhr.response));

试试这个以了解区别:

<script>
x = new String("hello");
alert(typeof x); //prints Object (this is a String object)

x = String("hello"); //or x = "hello";
alert(typeof x); //prints string (this is string with small s - similar to running toString() on a JS object)
</script>
于 2012-09-26T16:53:30.870 回答