使用Flask和jQuery上传文件

2024-10-03 15:35:47 发布

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

我在jQuery中编写一个使用ajax调用发送html表单的程序时遇到了问题。 这是我的上传.html以及表格.js文件:

$(document).ready(function() { $('form').on('submit', function(event) { $.ajax({ type : 'POST', url : '/uploadhc', data : $('#hc') }) .done(function(data) { if (data.error) { $('#errorAlert').text(data.error).show(); $('#successAlert').hide(); } else { $('#successAlert').text(data.file).show(); $('#errorAlert').hide(); } }); event.preventDefault(); }); }); ^{pr2}$

这是我的烧瓶服务器:

import os
from flask import Flask, render_template, request, jsonify

app = Flask(__name__)
APP_ROOT = os.path.dirname(os.path.abspath(__file__))

@app.route("/")
def index():
    return render_template("upload.html")


@app.route("/uploadhc", methods=['POST'])
def uploadhc():
    target = os.path.join(APP_ROOT, "DataSource/")


    if not os.path.isdir(target):
        os.mkdir(target)
    print request.files
    if 'file' not in request.files:
        error = "Missing data source!"
        return jsonify({'error': error})


    file = request.files['file']
    fileName = "DCData.csv"
    destination = '/'.join([target, fileName])
    file.save(destination)


    success = "Success!"
    return jsonify({'file': success})


if __name__ == "__main__":
    app.run(port=4555, debug=True)

当我试图选择一个csv文件并提交HTML表单时,服务器显示请求.files是不可变的multidict([]),它是空的。你知道怎么把文件发送到我的服务器吗?谢谢!在


Tags: 文件path服务器apptargetdataifos
3条回答

当我过去这样做的时候,我总是把enctype="multipart/form-data"放在formdiv中

下面是几个详细解释的链接:

在html侧:

<input type="file" id="uploadfile" name="NewCsvUpload">

在javascript端:

^{pr2}$

在服务器端:::

@app.route('/uploadLabel',methods=[ "GET",'POST'])
def uploadLabel():
    isthisFile=request.files.get('file')
    print(isthisFile)
    print(isthisFile.filename)
    isthisFile.save("./"+isthisFile.filename)

您需要将表单作为多部分上传发送,您可以使用FormData(formElement)将整个表单转换为

var form = $('#upload-hc')[0]
var fd = new FormData(form)

$.ajax({
  type : 'POST',
  url : '/uploadhc',
  data: fd,
  processData: false,  // tell jQuery not to process the data
  contentType: false   // tell jQuery not to set contentType
})

如果你有兴趣的话,这里有一个es6版本

和13;

和13;

相关问题 更多 >