将post数据从javascript发送到python服务器

2024-07-05 14:09:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用JavaScript录制音频并将其发送到Python服务器。到目前为止,我已经运行了它,记录运行良好。使用AJAX发布和获取数据,我试图传递它,但发送到Python不起作用

这是我的密码:

JavaScript:

function submit(blob) {
  var reader = new window.FileReader();
  reader.readAsDataURL(blob);
  reader.onloadend = function() {
    var fd = new FormData();
    base64data = reader.result;
    console.log(base64data);
    fd.append('file', base64data, 'audio.ogg');
    $.ajax({
      type: 'POST',
      url: '/',
      data: fd,
      cache: false,
      processData: false,
      contentType: false,
      enctype: 'multipart/form-data'
    }).done(function(data) {
      console.log(data);
    });
  }

Python服务器:

from flask import Flask, render_template, request

    app = Flask(__name__)

    @app.route('/')

    def home():

        return render_template("index.html")

     @app.route('/', methods=['POST', 'GET'])
     def get_data():
             with open('./audio.ogg', 'wb') as f:
                 f.write(request.data)
             f.close()
             print("FILE CLOSED")
             return render_template("index.html")

    if __name__ == '__main__':

      app.run(debug=True)

Tags: 服务器falseappnewdatavarfunctiontemplate
1条回答
网友
1楼 · 发布于 2024-07-05 14:09:56

在JavaScript中,如果您试图将字符串作为文件发送,则应该发送一个文件/blob。
见下文

function submit(blob) {
    var fd = new FormData();
    fd.append('file', blob, 'audio.ogg');
    $.ajax({
      type: 'POST',
      url: '/',
      data: fd,
      cache: false,
      processData: false,
      contentType: false
    }).done(function(data) {
      console.log(data);
    });
}

在服务器端代码中,应该使用request.files访问上载的文件

from flask import Flask, render_template, request

    app = Flask(__name__)

    @app.route('/')

    def home():

        return render_template("index.html")

     @app.route('/', methods=['POST', 'GET'])
     def get_data():
             request.files["file"].save('./audio.ogg')
             print("FILE CLOSED")
             return render_template("index.html")

    if __name__ == '__main__':

      app.run(debug=True)

相关问题 更多 >