Flask中的Ajax文件上传 - 浏览器中的json响应而不是成功调用

时间:2017-08-23 22:02:32

标签: jquery python ajax flask flask-wtforms

所以我正在尝试使用ajax上传一个文件,该文件似乎上传正常但是在表单验证后从我的视图返回响应时它不会进入我的ajax函数但它似乎是我的浏览器只显示一个显示json的白色屏幕

这是我的一些代码 - ajax请求 - 使用jquery 2.0.3

            var form_data = new FormData($('#firmware_file')[0]);
            var url = "{{ url_for('update.update_firmware') }}";
            $.ajax({
                type: 'POST',
                url: url,
                data: form_data,
                processData: false,
                contentType: 'application/json',
                cache: false,
                async: false,
                success: function(data) {
                    console.log("YES I DO STUFF HERE IT NEVER FIRES");
                }
            });

烧瓶表格处理

if form2.validate_on_submit():
    uploaded_file = request.files[form2.firmware_file.name]
    file_data = uploaded_file.read()
    return_data = {}
    return_data['uploading'] =  'blerg' #uploaded_file.filename
    file_path = os.path.join('/tmp', secure_filename(uploaded_file.filename))
    open(file_path, 'w').write(file_data)

    APP.decoder.firmware_file = file_path
    APP.decoder.firmware_length = len(filter(lambda x: x[0] == ':', file_data) )

    return jsonify(return_data)

这是表单定义

<form id="uploader_manual" class="form-box " method="POST" action="/update/update_firmware" enctype="multipart/form-data">
<div class="control-group">
    <label class="control-label" for="firmware_file">
    <label for="firmware_file">Firmware File</label>
    </label>
<div class="controls">
    <input class="firmware_file" id="firmware_file" name="firmware_file" type="file">
    <span class="help-inline"></span>

</div>
</div>                  
<span id="submit-group" class="control-group">
    <span class="form-actions">
        <input class="btn btn-primary" id="submit" name="submit" value="Upload" type="submit">
    </span>
</span>
</form>

这似乎只是通过我的“上传”返回一个白色屏幕:“filename”json。

完整的瓶子视图:

@updater.route('/update_firmware', methods=['GET', 'POST'] )
@login_required
@admin_required
def update_firmware():
    current_firmware = APP.decoder.device.version_number
    all_ok = "true"
    form = UpdateFirmwareJSONForm()
    form2 = UpdateFirmwareForm()
    form2.multipart = True
    form.firmware_file_json.choices = []
    data = None
    try:
        response = urllib.urlopen(FIRMWARE_JSON_URL)
    except IOError:
        flash('Cannot connect to server', 'error')
        all_ok = "false"

    if all_ok is "true":
        data = json.loads(response.read())

        counter = 0
        for firmware in data['firmware']:
            form.firmware_file_json.choices.insert(counter,(firmware['file'], firmware['version']))
            counter = counter + 1

    if form.validate_on_submit():
        file_name = form.firmware_file_json.data
        zip, headers = urllib.urlretrieve(file_name)
        return_data = {}

        with zipfile.ZipFile(zip) as zf:
            files = [name for name in zf.namelist() if name.endswith('.hex')]
            for filename in files:
                file_path = os.path.join('/tmp', secure_filename(filename))
                file_data = zf.open(filename, 'r').read()
                return_data['uploading'] = filename
                if not os.path.isfile(file_path):
                    open(file_path, 'w').write(file_data)

                APP.decoder.firmware_file = file_path
                APP.decoder.firmware_length = len(filter(lambda x: x[0] == ':', file_data) )

            zf.close()
        return jsonify(return_data);

    if form2.validate_on_submit():
        uploaded_file = request.files[form2.firmware_file.name]
        file_data = uploaded_file.read()
        return_data = {}
        return_data['uploading'] =  uploaded_file.filename
        file_path = os.path.join('/tmp', secure_filename(uploaded_file.filename))
        open(file_path, 'w').write(file_data)

        APP.decoder.firmware_file = file_path
        APP.decoder.firmware_length = len(filter(lambda x: x[0] == ':', file_data) )


        return jsonify(return_data)

    return render_template('updater/firmware_json.html', current_firmware=current_firmware, form=form, form2=form2, firmwarejson=data, all_ok=all_ok);

2 个答案:

答案 0 :(得分:0)

对于大多数情况,主要问题在于将contentType设置为某些内容。以下两件事都设置为false:

  
      
  1. processData - 因为jQuery会将文件数组转换为字符串,服务器无法接收它。
  2.   
  3. contentType - 将此设置为false,因为jQuery默认为application / x-www-form-urlencoded并且不发送文件。
  4.   

看看这是否是您面临的问题。

答案 1 :(得分:-1)

我只是没有及早阻止按钮的默认操作。