首页 > 解决方案 > 如何使用 Axios 将文件从 ReactJs 发送到 Flask

问题描述

我正在尝试使用 axios 调用将文件从 ReactJs 前端发送到烧瓶后端。

这是我的 axios 调用:

            const audio_file = new File(buffer, 'recording.mp3', {
                type: blob.type,
                lastModified: Date.now()
            });
            const blobURL = URL.createObjectURL(blob);
            this.setState({blobURL, isRecording: false, recorded:true})

            
            let options = {
                method: 'POST',
                url: flaskEndpoint + "audio/1",
                file: audio_file,
                crossOrigin:'*'
            }

            console.log(options)

            axios(options)
                .then(response => {
                    console.log(response)
                })
                .catch(error => {
                    console.log("Error in the axios call:" + error);
                })

目前我的烧瓶方法如下所示:

@app.route('/audio/<int:user_id>', methods=['POST'])
@cross_origin()
def make_audio(user_id):
    print(request.files.get('recording.mp3'))
    print(request.files)

    return 0

这是python应用程序的控制台:

在此处输入图像描述

这是 React App 的 Web 控制台:

在此处输入图像描述

我在这里犯错了吗?

编辑

好的,我尝试了将文件转换为 base64 然后将文件发送到后端的建议。

这是我的新 axios 调用。

let options = {
                method: 'POST',
                url: flaskEndpoint + "audio/1",
                data: convertBlobToBase64(blob),
                // file: audio_file,
                crossOrigin:'*',
                headers: {
                    'Content-Type': 'application/json'
                },
                json: true
            }

            console.log(options)

            axios(options)
                .then(response => {
                    console.log(response)
                })
                .catch(error => {
                    console.log("Error in the axios call:" + error);
                })

        });

这是 convetBlobtoBase64 函数(借自:https ://gist.github.com/n1ru4l/dc99062577b746e0783410b1298ab897 )

const convertBlobToBase64 = blob => new Promise((resolve, reject) => {
    const reader = new FileReader;
    reader.onerror = reject;
    reader.onload = () => {
        resolve(reader.result);
    };
    reader.readAsDataURL(blob);
});

这是发送到后端的内容: 在此处输入图像描述

我认为这回答了我的问题,尽管我将创建另一个来解决如何访问烧瓶端的数据。

标签: reactjsflaskaxios

解决方案


推荐阅读