javascript - 传出数据的 XmlHttpRequest overrideMimeType

标签 javascript ajax xmlhttprequest

我希望 XmlHttpRequest 不接触(即转换为 UTF-8 或任何其他编码)它向/从服务器发送和接收的任何字符。

对于从服务器接收到的字符,我知道我可以执行 XmlHttpRequest#overrideMimeType('text/plain; charset=x-user-defined') 并且字符单独保留。

但是,对于通过 XmlHttpRequest#send 调用发送到服务器的字符,我找不到告诉 XmlHttpRequest 不要接触这些字符的方法。我看到 XmlHttpRequest 将它们编码为 UTF-8,无论我尝试了什么。有办法避免这种情况吗?

最佳答案

我遇到了一个类似的问题来上传从麦克风(通过闪光灯)抓取的音频。 这是我解决它的方法(在 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)

关于javascript - 传出数据的 XmlHttpRequest overrideMimeType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5165337/

相关文章:

javascript - 关于在 JavaScript 中创建对象的问题

javascript - vim格式化JS错误

javascript - 仅在 IE9 上存在的 ajax 调用中的访问被拒绝

php - 中止 jquery ajax 时中止 php 脚本执行

xmlhttprequest - Internet Explorer : SCRIPT7002: XMLHttpRequest: Network Error 0x2f7d, 由于错误 00002f7d 无法完成操作

javascript - TinyMCE - 防止自动聚焦于 mceAddControl 命令

javascript - 现代 JavaScript 引擎执行哪些优化?

javascript - 没有 CORS 或 JSONP 的跨域请求

cookies - 如果有来自 xmlhttprequest 的 set-cookie 响应,浏览器是否会接受它并设置 cookie?

javascript - 多选不起作用,并给出错误 'this.validator is not a function' - Angular2