javascript - Request.files 返回空
问题描述
我正在尝试将一个 wav 文件从我的 HTML 页面发送到我的烧瓶后端。我已经查看了类似的问题,这些问题说要将name=file
标签添加到表单属性,enctype=multipart/form-data
但我仍然没有在后端收到文件。Request.files 包含一个空的ImmutableMultiDict([])
我也尝试添加audio/wav
<html>
<form method="post" enctype="multipart/form-data">
<div>
<label>Select file to upload</label>
<input type="file" id="fileinput" name="file">
</div>
<button type="submit" value=Upload>Convert</button>
</form>
<script>
// Select your input type file and store it in a variable
const input = document.getElementById('fileinput');
// This will upload the file after having read it
const upload = (file) => {
var prod = 'https://elementa-backend-staging.herokuapp.com/wrapper/v1/file';
var debug = 'http://127.0.0.1:5000/wrapper/v1/file';
console.log("Sending file: " + file);
fetch(debug, { // Your POST endpoint
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: file // This is your file object
}).then(
response => console.log(response.json()) // if the response is a JSON object
).then(
success => console.log("Test succeeded: " + success) // Handle the success response object
).catch(
error => console.log("Test failed: " + error) // Handle the error response object
);
console.log(file[0]);
};
// Event handler executed when a file is selected
const onSelectFile = () => upload(input.files);
// Add a listener on your input
// It will be triggered when a file will be selected
input.addEventListener('change', onSelectFile, false);
</script>
</html>
后端:
from flask import Flask, request, abort, jsonify
import speech2new # this will be your file name; minus the `.py`
from flask_cors import CORS, cross_origin
wrapper = Flask(__name__)
cors = CORS(wrapper)
UPLOAD_FOLDER = '/uploads'
wrapper.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
ALLOWED_EXTENSIONS = {'wav', 'png', 'jpeg'}
@wrapper.route('/wrapper/v1/file', methods=['POST'])
def mozdhe():
#Pass the request parameters (containing the .WAV file) to the Speech-to-Text
return jsonify(speech2new.get_file(request))
if __name__ == '__main__':
wrapper.run(host='127.0.0.1', port='5000', debug=True)
#speech2new.py get_file 函数
def get_file(request):
#Outlier case: No file
print(request.files)
if 'file' not in request.files:
return json.dumps("You did not send a file ")
file = request.files['file']
#Outlier case: Invalid filename (not parse-able)
if file.filename == "":
return json.dumps("The application didn't assign a filename.")
#Ideal case: Audio file recieved in Byte Form, pass to Mozhde's Library
file.save('recievedAudio')
predict = dict({'result':get_large_audio_transcription(file)})
#data = json.dumps(predict)
return predict
解决方案
要通过 fetch 进行多部分/表单数据文件上传,您必须使用 FormData 对象作为您使用文件列表的数据参数
// This will upload the file after having read it
const upload = (file) => {
var prod = 'https://elementa-backend-staging.herokuapp.com/wrapper/v1/file';
var debug = 'http://127.0.0.1:5000/wrapper/v1/file';
var formData = new FormData();
// Add file to formdata object
formData.append("file", file); // Use "file" as thats what the server expects
console.log("Sending file: " + file);
fetch(debug, { // Your POST endpoint
method: 'POST',
body: formData// This is your form data object
}).then(
response => console.log(response.json()) // if the response is a JSON object
).then(
success => console.log("Test succeeded: " + success) // Handle the success response object
).catch(
error => console.log("Test failed: " + error) // Handle the error response object
);
console.log(file);
};
// Event handler executed when a file is selected
const onSelectFile = () => upload(input.files[0]); // send the file
推荐阅读
- r - 一列的一部分是否存在于另一列中?R
- ios - 是否可以使用 SCNAudioPlayer() 进行音频电平测量
- python - 如何在python中找到小说中所需的单词?
- javascript - ExtJS Classic:为窗口的 x/y/width/height 设置动画时,标题未在指定的最终位置结束
- java - 在导航栏中更改片段时进度消失
- python - sklearn knn分类器的pred()函数可以将scipy稀疏矩阵作为输入吗?
- spring - SpringBoot ReloadableResourceBundleMessageSource 找不到属性文件
- python - 如何在 Docker 中保留 dotenv 机密?
- reactjs - React fetch API 与图表中的实时数据
- python - Spoitpy 当前播放