通过 HTTP 在 JavaScript 中发送二进制数据 [英] Sending binary data in javascript over HTTP

查看:33
本文介绍了通过 HTTP 在 JavaScript 中发送二进制数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向网络上的设备发送 HTTP POST.不幸的是,我想向设备发送四个特定字节的数据,我似乎只能向设备发送字符串.反正有没有使用javascript发送原始二进制文件?

I'm trying to send a HTTP POST to a device on my network. I want to send four specific bytes of data to the device unfortunately I only seem to be able to send strings to the device. Is there anyway to send raw binary using javascript?

这是我用来执行 POST 的脚本,它目前不会运行,除非我在数据字段中放入一个字符串.有什么想法吗?

Here's the script I'm using to do the POST, it currently doesn't run unless I put a string in the data field. Any ideas?

(function ($) {
   $.ajax({
      url: '<IP of Address>',
      type: 'POST',
      contentType: 'application/octet-stream',

      //data:'253,0,128,1',
      data:0xFD008001,

      crossDomain: true
   });
})(jQuery);

推荐答案

默认情况下,jQuery 序列化数据(在 data 属性中传递) - 这意味着 0xFD008001 number 作为 '4244668417' string(10 个字节,而不是 4 个)被传递给服务器,这就是为什么服务器不按预期处理它的原因.

By default, jQuery serializes the data (passed in data property) - and it means 0xFD008001 number gets passed to the server as '4244668417' string (10 bytes, not 4), that's why the server treats it not as expected.

有必要通过将 $.ajax 属性 processData 设置为 false 来防止这种行为:

It's necessary to prevent such behaviour by setting $.ajax property processData to false:

默认情况下,数据作为对象传入数据选项(从技术上讲,除字符串之外的任何内容)将被处理并转换为查询字符串,适合默认的内容类型应用程序/x-www-form-urlencoded".如果你想发送一个DOMDocument 或其他未处理的数据,将此选项设置为 false.

By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.

...但这只是整个故事的一部分:XMLHttpRequest.send 实现有它自己的 限制.这就是为什么我认为最好的选择是使用 TypedArrays 制作自己的序列化程序强>:

... but that's only part of the whole story: XMLHttpRequest.send implementation has its own restrictions. That's why your best bet, I suppose, is to make your own serializer using TypedArrays:

// Since we deal with Firefox and Chrome only 
var bytesToSend = [253, 0, 128, 1],
    bytesArray = new Uint8Array(bytesToSend);

$.ajax({
   url: '%your_service_url%',
   type: 'POST',
   contentType: 'application/octet-stream',  
   data: bytesArray,
   processData: false
});

或者根本不使用 jQuery:

Or without using jQuery at all:

var bytesToSend = [253, 0, 128, 1],
    bytesArray = new Uint8Array(bytesToSend);

var xhr = new XMLHttpRequest();
xhr.open('POST', '%your_service_url%');
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.send(bytesArray);

这篇关于通过 HTTP 在 JavaScript 中发送二进制数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆