XmlHttpRequest的overrideMimeType用于传出数据的类型设置

5

我希望XmlHttpRequest不要更改发送和接收到/从服务器的任何字符,包括将其转换为UTF-8或任何其他编码方式。

对于从服务器接收的字符,我知道我可以使用XmlHttpRequest#overrideMimeType('text/plain; charset=x-user-defined')来保留这些字符。

然而,对于通过XmlHttpRequest#send调用发送到服务器的字符,我找不到一种方法告诉XmlHttpRequest不要更改这些字符。无论我尝试什么,XmlHttpRequest都会将它们编码为UTF-8。有没有办法防止这种情况发生?


你解决了这个问题吗?我被卡住了。 - wildabeast
2个回答

2

我遇到了一个类似的问题,需要上传从麦克风(通过flash)抓取的音频。 这是我解决它的方法(在FF 9和chromium 15中测试过)。以下js代码将二进制输入作为字符串接收,并上传到服务器而不进行任何更改/编码。 希望这对某些人有所帮助。

    var audioBytes = <the data you want sent untouched>
    var crlf = '\r\n';
    var body = '';
    var doubleDash = '--';
    var boundary = '12345678901234567890';

    var file = {
            name: "online-recording.wav",
            type: "audio/x-wav",
            size: audioBytes.length,
            recordedContent: audioBytes
    };

    var body = doubleDash + boundary + crlf +
            'Content-Disposition: form-data; name="file"; ' +
            'filename="' + unescape(encodeURIComponent(file.name)) + '"' + crlf +
            'Content-Type: ' + file.type + crlf + crlf +
            file.recordedContent + crlf +
            doubleDash + boundary + doubleDash + crlf;

    // copy binary content into a ByteArray structure, so that the browser doesn't mess up encoding
    var audioByteArray = new Uint8Array(body.length);

    for (var i=0; i< audioByteArray.length; i++) {
            audioByteArray[i] = body.charCodeAt(i);
    }

    // use an XMLHttpRequest to upload the file
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
                    console.log(xhr.readyState);
    };
    xhr.open('post', url, true);
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

    // setup AJAX event handlers here

    xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
    xhr.send(audioByteArray.buffer);

诀窍在于使用ArrayBuffer构建请求,这被视为二进制数据,因此浏览器不会干扰它。或者,如果您只针对Firefox,则可以使用xhr.sendAsBinary()(据我所知,它未移植到任何其他浏览器,而上述代码似乎符合W3C标准)。


+1,这在 https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Sending_binary_data 中有描述,并且显然是在FF9中新出现的。 - Potatoswatter

0

你可以尝试使用base64对发送的数据进行编码。据我所知,无论采用什么编码(UTF-8 / Latin-1 / 等),这都是有效的。


是的,但那样我就需要在服务器上解码base64,这样就失去了意义。我希望字符按原样发送到服务器。 - Mete Atamel
是的,但据我所知,这是确保服务器收到的所有内容实际上是客户端发送的内容的最佳方法。另外,只需使用UTF-8解码您的字符串即可 :) 我认为您应该拥有原始字符串。 - Zsub

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接