Dropzone在上传到Flask应用程序后不会重定向

2024-03-28 19:59:26 发布

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

我正在写一个资源,用Dropzone把文件上传到一个Flask应用程序。文件上传后,应用程序应该重定向到hello world页面。这是不会发生的,应用程序被卡在上传文件的视图上。我使用的是jquery3.1.0和master的Dropzone。在

from flask import Flask, request, flash, redirect, url_for render_template)
from validator import Validator

ALLOWED_EXTENSIONS = set(['csv', 'xlsx', 'xls'])

def allowed_file(filename):
    return (filename != '') and ('.' in filename) and \
           (filename.split('.')[-1] in ALLOWED_EXTENSIONS)

def create_app():
    app = Flask(__name__)
    app.secret_key = 'super secret key'
    return app

app = create_app()

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

@app.route('/world')
def hello_world():
    return render_template('hello_world.html')

@app.route('/upload', methods=['POST'])
def upload():
    # check that a file with valid name was uploaded
    if 'file' not in request.files:
        flash('No file part')
        return redirect(request.url)
    file = request.files['file']
    if not allowed_file(file.filename):
        flash('No selected file')
        return redirect(request.url)

    # import ipdb; ipdb.set_trace()
    validator = Validator(file)
    validated = validator.validate()
    if validated:
        flash('Success')
    else:
        flash('Invalid file')
    return redirect(url_for('hello_world'))

if __name__ == '__main__':
    app.run(debug=True)
^{pr2}$

Tags: 文件app应用程序urlflaskhelloworldreturn
2条回答

我对dropzone不太熟悉,但我将从我的一个flask应用程序中给出一个使用文件上传的例子。我只是用标准的HTML上传表单。希望从这里你应该能知道发生了什么。在

注意,我没有使用模板来上传文件。在

def index():
    return """<center><body bgcolor="#FACC2E">
    <font face="verdana" color="black">
    <title>TDX Report</title>
    <form action="/upload" method=post enctype=multipart/form-data>
    <p><input type=file name=file>
    <input type=submit value=Upload>
    </form></center></body>"""

# here is my function that deals with the file that was just uploaded
@app.route('/upload', methods = ['GET', 'POST'])
def upload():
    if request.method == 'POST':
        f = request.files['file']
        f.save(f.filename)
        # process is the function that i'm sending the file to, which in this case is a .xlsx file
        return process(f.filename)

我在这一行设置post file upload的路由路径:

^{pr2}$

你的问题可能是这条线: <form action="upload" method="post" class="dropzone dz-clickable" id="demo-upload" multiple>upload之前缺少/。在

我在flask应用程序中遇到了类似的问题,我用以下jQuery函数解决了这个问题:

Dropzone.options.myDropzone = {

autoProcessQueue: false,

init: function() {
    var submitButton = document.querySelector("#upload-button");
    myDropzone = this;

    submitButton.addEventListener("click", function() {
        myDropzone.processQueue();
    });

    this.on("sending", function() {
        $("#myDropzone").submit()
    });
  }
};

在发送文件之前调用参数“sending”,这样我就可以提交dropzone表单了。有了这些,我的flask应用程序中的所有重定向都可以正常工作。在

为了清晰起见,我的html代码片段:

^{pr2}$

相关问题 更多 >