XMLHttpRequest发送FormData(加入Blob),java后端接收返回结果,前端接收结果

时间:2022-12-22 21:09:09
 
 
 //上传
        this.upload = function (url, callback) {
            var fd = new FormData();
            fd.append("audioData", this.getBlob());
            //用ajax方法,后台controller拿不到文件,有知道的希望通知我,一起进步
            // $.ajax({
            //     type: "POST",
            //     url: url,
            //     data:fd,
            //     cache:false,
            //     processData: false,
            //     contentType: false,
            //     success:function (result) {
            //         callback(result);
            //     }
            // });
            var xhr = new XMLHttpRequest();
            if (callback) {
                //上传过程回调
                // xhr.upload.addEventListener("progress", function (e) {
                //     callback('uploading', e);
                // }, false);
                //上传完成回调
                xhr.addEventListener("load", function (e) {
                    callback('ok', e);
                    //e.target.responseText即后台返回结果
                    var result=e.target.responseText;
                }, false);
                xhr.addEventListener("error", function (e) {
                    callback('error', e);
                }, false);
                xhr.addEventListener("abort", function (e) {
                    callback('cancel', e);
                }, false);
            }
            xhr.open("POST", url);
            xhr.send(fd);
        }


后端controller代码:

public JSONObject speechRecognize(@RequestParam(value = "audioData",required = false)MultipartFile file, HttpServletRequest request){
        JSONObject jsonObject=new JSONObject();
        boolean status=false;
        JSONArray speech=new JSONArray();
        if(file!=null){
            try {
                String speechResult= BaiduUtil.speechRecognition(file.getBytes());
                JSONObject speechResultJo= JSON.parseObject(speechResult);
                if(speechResultJo!=null && (Integer)speechResultJo.get("err_no")==0){
                    status=true;
                    speech= (JSONArray) speechResultJo.get("result");
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        jsonObject.put("status",status);
        jsonObject.put("speech",speech);
        return jsonObject;
    }