将 blob 发送到 python flask 然后保存
send blob to python flask and then save it
所以我正在尝试制作一个网站来录制您的声音,问题是当我将 blob 文件或 blob url 发送到烧瓶服务器时,我的烧瓶 python 代码说是没有内容,我怎样才能发送blob,以便服务器可以将其保存为文件。
mediaRecorder.addEventListener("stop", () => {
const audioBlob = new Blob(audioChunks, { type: "audio/wav" })
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.play();
var data = new FormData()
data.append('file', audioUrl)
fetch('http://127.0.0.1:5000/receive', {
method: 'POST',
body: data
}).then(response => response.json()
).then(json => {
console.log(json)
});
和我的 python 烧瓶代码:
@app.route("/receive", methods=['post'])
def form():
files = request.files
file = files.get('file')
print(file)
with open(os.path.abspath(f'backend/audios/{file}'), 'wb') as f:
f.write(file.content)
response = jsonify("File received and saved!")
response.headers.add('Access-Control-Allow-Origin', '*')
return response
有办法吗?发送记录 blob 文件,将其下载到 python?
问题出在这一行:
data.append('file', audioUrl)
您 FormData.append 的使用方式不正确。
应该是:
data.append('file', audioBlob , 'file')
查看文档:https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
所以我正在尝试制作一个网站来录制您的声音,问题是当我将 blob 文件或 blob url 发送到烧瓶服务器时,我的烧瓶 python 代码说是没有内容,我怎样才能发送blob,以便服务器可以将其保存为文件。
mediaRecorder.addEventListener("stop", () => {
const audioBlob = new Blob(audioChunks, { type: "audio/wav" })
const audioUrl = URL.createObjectURL(audioBlob);
const audio = new Audio(audioUrl);
audio.play();
var data = new FormData()
data.append('file', audioUrl)
fetch('http://127.0.0.1:5000/receive', {
method: 'POST',
body: data
}).then(response => response.json()
).then(json => {
console.log(json)
});
和我的 python 烧瓶代码:
@app.route("/receive", methods=['post'])
def form():
files = request.files
file = files.get('file')
print(file)
with open(os.path.abspath(f'backend/audios/{file}'), 'wb') as f:
f.write(file.content)
response = jsonify("File received and saved!")
response.headers.add('Access-Control-Allow-Origin', '*')
return response
有办法吗?发送记录 blob 文件,将其下载到 python?
问题出在这一行:
data.append('file', audioUrl)
您 FormData.append 的使用方式不正确。 应该是:
data.append('file', audioBlob , 'file')
查看文档:https://developer.mozilla.org/en-US/docs/Web/API/FormData/append