【发布时间】:2021-06-20 22:26:54
【问题描述】:
我正在尝试将一个 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
【问题讨论】:
标签: javascript http flask