reactjs - 如何使用 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);
});
我认为这回答了我的问题,尽管我将创建另一个来解决如何访问烧瓶端的数据。
解决方案
推荐阅读
- javascript - Bootstrap 4 Popover 内联样式问题
- dafny - 有没有办法在 dafny 中读取类对象数组的字段
- git - Gitkraken:显示 repo 中的所有文件
- python - 如何使用 python 脚本访问 XHR 数据?
- java - 将特定的字符串格式转换为 json
- javascript - 为什么我在使用 Selenium-webdriver 运行测试时不断收到“UnhandledPromiseRejectionWarning”?
- spring - 如何将作业从 Spring 项目持久化到 H2 数据库
- slurm - 是否可以使用 Slurm 在 chroot 环境中运行用户的作业
- r - 如何在大数据集中找到大于 x、x+10000 的值的相对频率?
- entity-framework - 实体框架:基于最后一级子实体的过滤器