如何使用JavaScript的数组类型接收服务端响应的二进制数据(byte[]形式)

背景

最近在一个项目中遇到一个场景:需要服务器端发送字节数组byte[]给客户端,后台采用Java提供接口,前段采用HTML + JavaScript访问接口。

解决方案

服务器端

服务器端比较简单,直接提供一个接口即可,接口返回 byte[ ] 数组。

package com.xl.projects.interactiondemo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *  
 * @author Administrator
 *
 */
@RestController
public class ByteArrayInteractionController {
    
    
	
	@GetMapping("/get")
	public byte[] byteArrayInteraction(HttpServletResponse response) {
    
    
		response.setHeader("Access-Control-Allow-Origin", "*");// 解决跨域问题
		// 这里为了测试直接创建的一个byte数组,
		// 实际应用的时候可根据具体的业务需求将图片、文件、文字、数字等转成byte数组
		byte[] bts = new byte[] {
    
    1,23,22,21,55}; 
		return bts;
	}
}

浏览器输入地址(这里的接口是发布在本机上的):localhost:8080/get
在这里插入图片描述
如图显示为乱码(这是因为浏览器默认的设置导致的),不过,没关系这一步主要是验证接口可以正常访问。客户端要想得到期望的数据 byte[],则需要使用XMLHttpReqeust来请求接口。

客户端

客户端的代码才是该问题的重点!!
使用的主要技术点是XMLHttpReqeust,为什么XMLHttpReqeust可以解决这个问题?原因在于:XMLHttpReqeust的对应有一个responseType属性,通过设置该属性的值可以改变服务器端返回的响应类型。responseType的取值可以是“arraybuffer”、“blob”、“document”、“json”以及“text”,默认值是“”(空串)。另外一个属性response用于接收不同类型的responseType返回的实体,即是如果responseType="arraybuffer"则返回的response的内容为byte[],如果responseType="json"则返回的response的内容为json。下面为代码:

<!DOCTYPE html>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<head>
    <title>Welcome</title>
    <script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.min.js"></script>
</head>
 
<body>
    <div style="margin: auto;text-align: center">
        <h1>Welcome hahha1 </h1>
    </div>
    
</body>
 
 
<script type="text/javascript">

var oReq = new XMLHttpRequest();
oReq.open("GET", "http://127.0.0.1:8080/get", true);
oReq.responseType = "arraybuffer";

oReq.onload = function (oEvent) {
    
    
  var arrayBuffer = oReq.response; // Note: not oReq.responseText
  if (arrayBuffer) {
    
    
  
    var byteArray = new Uint8Array(arrayBuffer);
	
    for (var i = 0; i < byteArray.byteLength; i++) {
    
    
      // do something with each byte in the array
	  console.log(byteArray[i]);
    }
  }
};

oReq.send(null);

</script>
 
</html>

将以上html文件使用浏览器打开,打开浏览器控制台即可看到接收到byte[ ] ,客户端接收到byte[ ]数组后就可以根据具体的业务需求进行操作该byte[ ]了。
在这里插入图片描述
***参考资料:***https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

猜你喜欢

转载自blog.csdn.net/qq_29025955/article/details/108090379