首页 > 解决方案 > 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

标签: javascripthttpflask

解决方案


要通过 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 

推荐阅读