从XMLHttpRequest读取原始字节

从XMLHttpRequest读取原始字节

本文介绍了Javascript:从XMLHttpRequest读取原始字节-搞砸了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用这个原始问题的代码片段:使用JavaScript而不是jQuery从二进制文件中读取字节

I'm playing with the code snippet from this original question: Read bytes from a binary file with JavaScript, without jQuery

但是,由于某些原因,似乎加载了一组完全不同的字节!我怀疑这与字符串转换有关.

However, for some reasons, a whole different set of bytes appear to be loaded! I suspect this has to do with the string conversion.

这是我要下载的二进制文件的副本: http://steeman. dk/html5/coco/colorbasic13.rom

Here's a copy of the binary file I am trying to download: http://steeman.dk/html5/coco/colorbasic13.rom

在本地IIS 7.5服务器中,我已将.rom MIME类型添加为"application/octet-stream"(我也尝试过"text/plain; charset = x-user-defined",结果相同).

To my local IIS 7.5 server I have added the .rom MIME type as 'application/octet-stream' (I have also tried with 'text/plain; charset=x-user-defined' with the same results).

期望是从此开始的一系列字节:

What I'm expecting is a sequence of bytes starting with this:

a1 cb a2 82 a7 7c a7 0b a7 f4 a9 de a7 d8 10 ce (etc.)

但是,我得到的内容如下:

fd e2 fd fd 7c fd 0b fd fd fd a7 fd 10 fd 03 c6 37 fd fd 23 (etc.)

除了很多"fd"被散布外,我并没有真正看到清晰的图案.是什么赋予了?

I am not really seeing a clear pattern apart from a lot of 'fd' being intersparsed. What gives?

BTW是否有使用JQuery进行此操作的更简单方法?

BTW is there an easier way of doing this using JQuery?

推荐答案

使用Uint8Array并将响应类型设置为"arraybuffer",好像有一种新方法:

Looks like there is a new way, by using Uint8Array and setting the response type to "arraybuffer":

function loadRom(file, callback)
{
   var xhr = new XMLHttpRequest();
   xhr.open('GET', file, true);
   xhr.responseType = 'arraybuffer';
   xhr.onload = function (e)
   {
    if (this.status == 200)
    {
        var bytes = new Uint8Array(this.response);
        callback(bytes);
    }
  }
xhr.send();
}

这对我有用!

这篇关于Javascript:从XMLHttpRequest读取原始字节-搞砸了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 21:35