Flask中无法使用FormData()和jQuery处理文件上传

时间:2019-04-15 12:50:43

标签: python jquery forms flask

我正在尝试测试从html页面上传到Flask本地服务器的简单文件。

这是html代码

<form action="/" method="post">
  <div class="grid-container">
    <div class="grid-x grid-padding-x">
      <input type="text" name="test" id="test" placeholder=".medium-6.cell">
      <div class="cell small-6">
          <label for="exampleFileUpload" class="button">Choose File</label>
          <input type="file" id="exampleFileUpload" name="exampleFileUpload" class="show-for-sr">
      </div>
      <div class="cell small-6">
        <button type="submit" class="button secondary">Upload and test</button>
      </div>
    </div>
  </div>
</form>

这是javascript代码

<script>
  $("form").submit(function(event){

    event.preventDefault();

    var pictureInput = document.getElementById("exampleFileUpload");
    var myFormData = new FormData();
    myFormData.append('pictureFile', pictureInput.files[0]);

    // Display the key/value pairs
    for (var pair of myFormData.entries()) {
        console.log(pair[0]+ ', ' + pair[1]); 
    }

    $.ajax({
      url: 'http://127.0.0.1:5000/img-detect/',
      type: 'POST',
      data: myFormData,
      async: false,
      cache: false,
      dataType : 'json',
      processData: false,
      success: function (returndata) {
        console.log(returndata)
      }
    });

    return false;
  });
</script>

调试console.log打印pictureFile, [object File]

最后是烧瓶代码

from flask import Flask, jsonify, flash, request, redirect, url_for
from werkzeug.utils import secure_filename
from flask_cors import CORS
import os
app = Flask(__name__)
CORS(app)

UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['jpg', 'jpeg', 'gif'])

app.secret_key = 'super secret key'
app.config['SESSION_TYPE'] = 'filesystem'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/img-detect/', methods=['POST'])
def img_detect():
    print(request.files)
    # outputs ImmutableMultiDict([])

    if 'pictureFile' not in request.files:
        flash('No file part')
        return jsonify({'outcome': 'error 1'})

    file = request.files['pictureFile']
    # if user does not select file
    if file.filename == '':
        flash('No selected file')
        return jsonify({'outcome': 'error 2'})
    if file and allowed_file(file.filename):
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        return jsonify({'outcome': 'success'})

烧瓶始终返回error 1,而reques.files总是输出ImmutableMultiDict([])

关于我在做什么错的任何提示吗?

谢谢

1 个答案:

答案 0 :(得分:2)

在AJAX请求中发送二进制数据时,您需要设置contentType: falseprocessData: false

我还建议您删除async: false,因为这是非常糟糕的做法。您已经在success处理函数中处理了异步回调,因此无论如何都不必强制请求是同步的。