简体   繁体   English

ArrayBuffer疯狂-如何将二进制文件放入arraybuffer

[英]ArrayBuffer madness - how to get binary into an arraybuffer

This is doing my head in. 这是我的头脑。

I have a jquery ajax post returning output from a mysql database. 我有一个jquery ajax帖子从mysql数据库返回输出。 One field is binary. 一个字段是二进制的。 I wish to proccess that binary field using Javascript. 我希望使用Javascript处理该二进制字段。 I have been around and around in circles trying different approaches non of which seem satisfactory and most hit a road block. 我一直在兜圈子,尝试不同的方法,这些方法似乎都不令人满意,并且大多数都遇到了障碍。

I can pass the data up base64 encoded and then decode it in Javascript. 我可以将数据传递给base64编码,然后用Javascript解码。

The data is a packet so I wish to decode it using a DataView as it has all the Get... calls for treating the data as a packet ( like a C structure ). 数据是一个数据包,因此我希望使用DataView对其进行解码,因为它具有将数据视为数据包(如C结构)的所有Get ...调用。

I have tried Blobs and Typed Arrays but everwhere I go it seems to just not be the right thing. 我已经尝试过Blob和Typed Arrays,但是无论我走到哪里,似乎都不是对的。

What I am after is something like this: 我所追求的是这样的:

var ab = new ArrayBuffer ( atob( my_base64_encoded_packet_data )
var dv = new DataView ( ab );

Simple! 简单! No. The only way I have managed to get close is to using fileReader, like this ( roughly ): 不。我设法接近的唯一方法是使用fileReader,如下所示(大致):

fileReader.onload = function ( ) {
    var newBuf = this.result;
    callback( newBuf );
   return;
};
fileReader.readAsArrayBuffer( buf );

Where buf is a blob and newBuf is the ArrayBuffer. 其中buf是blob,而newBuf是ArrayBuffer。

Here is another approach which does what I want, but seems labour intensive. 这是另一种可以满足我需要的方法,但是似乎很费力。

function str2ab(str) {
  var buf = new ArrayBuffer(str.length);
  var bufView = new Uint8Array(buf);
  for (var i=0, var strLen=str.length; i<strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

Help please. 请帮助。 Thanks 谢谢

The problem is that you are using jQuery's ajax. 问题是您正在使用jQuery的ajax。 jQuery can't handle binary since it wants everything to be strings. jQuery无法处理二进制,因为它希望所有内容都是字符串。 Browser tries to be smart with it and tries to transform the response if you want to receive it as text 浏览器会尝试使其变得聪明,并且如果您想以文本形式接收它,则尝试转换响应

What you want is the raw binary so a responseType that is either arraybuffer or a blob is what you want. 您想要的是原始二进制文件,因此您想要的是arraybufferblobresponseType

The solution is either stick to doing xhr manually or use the new fetch method 解决方案是坚持手动执行xhr或使用新的提取方法

fetch(url, opts).then(res => res.arrayBuffer()).then(buffer => {
   // code here
})

Sending and Receiving Binary Data - MDN 发送和接收二进制数据-MDN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM