java post 403,通过Ajax发送FormData POST方法返回403

I write an application with speech recognition. All I want is to record some speech and send it to server where I will convert it into text. And I have a problem with sending that sound file. I record voice using p5.js library and when I try to download it there is no problem.

The problem is when I try to send it to server using ajax.

script.js

function toggleRecording(e) {

if (e.classList.contains("recording")) {

recorder.stop();

e.classList.remove("recording");

sendAudioToServer(soundFile)

} else {

e.classList.add("recording");

recorder.record(soundFile);

}

}

function sendAudioToServer(soundFile)

{

var data = new FormData();

data.append('fname', 'test.wav');

data.append('data', soundFile);

console.log(soundFile);

console.log(data);

$.ajax({

type: 'POST',

url: '/recognizeCommand',

data: data,

dataType: 'jsonp',

processData: false,

contentType: false,

success: function(data) {

alert("works!");

},

error: function() {

alert("not works!");

}

})

Java controller

@PostMapping("/recognizeCommand")

public @ResponseBody String recognizeCommand(@RequestParam MultipartFile mpf) {

try {

byte[] bytes = mpf.getBytes();

SpeechRecognitionApplication.logger.info(bytes);

} catch (IOException e) {

e.printStackTrace();

}

return "finish";

}

When I stop recording regardless to toggleRecording function it should stop recording and send it to server. And there is a problem with sendAudioToServer function. Here is the result from Chrome console:

mTHIK.png

KjSMr.png

I'm not sure but there is probably problem with FormData. As you can see when I printed it in console it's empty. Founded some similar questions here but there is no solution to solve my problem.

EDIT:

After add dataType: 'jsonp'

There is that error:

tFRt4.png

EDIT 2:

After adding csrf token:

Wxsix.png

解决方案

Please add csrf tokens as this.

In header:

var token = $("meta[name='_csrf']").attr("content");

var header = $("meta[name='_csrf_header']").attr("content");

Set headers.

$.ajax({

type: 'POST',

url: '/recognizeCommand',

data: data,

dataType: 'json',

processData: false,

contentType: false,

beforeSend: function(xhr) {

// here it is

xhr.setRequestHeader(header, token);

},

success: function(data) {

alert("works!");

},

error: function() {

alert("not works!");

}

})

Try adding debug point here.

SpeechRecognitionApplication.logger.info(bytes);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值