項(xiàng)目需求描述:
前端需要獲取后端音頻文件,但遇到跨域問(wèn)題,不能直接使用url獲取,需求必須使用流將文件傳到前端。因此,考慮Java后端讀取音頻文件,然后向前端發(fā)送數(shù)據(jù)流,前端按后端發(fā)送類型將數(shù)據(jù)接收,并合成其格式文件。
后端代碼舉例
@ResponseBody
@PostMapping("/getWavFile")
public ResponseEntity<byte[]> getUserVoiceprint(String fileName){
if(fileName == null || fileName == ""){
return null;
}
try{
String vpPath = "E:/files/wav/" + fileName + ".wav";
File f = new File(vpPath);
if(f.exists()){
byte[] file = Files.readAllBytes(f.toPath());
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Disposition", "attachment; filename=\"" + f.getName() +".wav\"");
ResponseEntity<byte[]> response = new ResponseEntity(file, headers, HttpStatus.OK);
return response;
}else{
return null;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
前端代碼舉例
引入axios.min.js文件文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-540280.html
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
axios({
method:"post",
url: "/getWavFile",
params: {fileName: wavName},
responseType:'arraybuffer',
headers: { 'Accept': '*/*', 'Content-Type': 'audio/wav' }
}).then(data => {
if(data.data.byteLength > 0){
blob = new Blob([data.data], {type: 'audio/wav'});
let audio = document.createElement('audio');
audio.src = URL.createObjectURL(blob);
audio.play();
}else{
alert("未查詢到記錄");
}
}).catch(function() {
alert("未查詢到記錄");
});
其中,responseType:‘a(chǎn)rraybuffer’,寫(xiě)成responseType:'blob’也可以;method也可以使用get,但此時(shí)不能使用params傳參。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-540280.html
到了這里,關(guān)于前端向Java后端請(qǐng)求blob、arraybuffer類型的數(shù)據(jù)流的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!