设备录音上传内容到服务器采用的是trunk协议,springboot 后端通过参数接收前端trunk协议内容很简单
下面介绍的是后端读取trunk协议完整内容的 两种方法
1 @RequestBody
例如:
@PostMapping("/xxx")
public String test(@RequestBody byte[] bs, HttpServletRequest request){
//bs 就是前端上传的trunk协议完整内容
//...
return "";
}
2 HttpServletRequest
注:通过读取InputStream 写入byte数组 即可,下面是我读取InputStream 的方法,也可以其他写法
@PostMapping("/xxx")
public String voiceTalkSpeex(@PathVariable("rid") String rid,@RequestBody byte[] bs, HttpServletRequest request){
byte[] bs = null;
try {
InputStream is = request.getInputStream();
ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
int rc = 0;
while ((rc = is.read(buff, 0, 1024)) > 0) {
swapStream.write(buff, 0, rc);
}
bs = swapStream.toByteArray();
} catch (Throwable e) {
e.printStackTrace();
}
return "";
}
实际开发中遇到的坑
上面获取trunk协议数据在正常情况是没问题的,但是如果项目中用到拦截器读取了post请求body内容就会导致后面的Controller方法中参数读取不到body内容,因为inputStream的内容读了一次就没了。
通过 自定义Filter 和 HttpServletRequestWrapper 实现拦截器读取body 且在controller方法中也能读取到body内容 。注意,如果遇到了在controller方法中参数读取到的trunk协议内容或其他字节流数据 比实际内容大了接近一倍。那么请看下我这篇博文的最后面介绍
《springboot 解决拦截器读取post请求输入流参数body内容后controller中 @RequestBody 参数无法读取body 内容问题》