Flask redirect doesn't work after upload

前端 未结 1 1065
天涯浪人
天涯浪人 2021-01-19 11:08

I basically want to go to a different page after the upload. What happens here is that the file is uploaded very quickly and saved on the server, but after that the client(m

相关标签:
1条回答
  • 2021-01-19 11:32

    Update: Now you can use Flask-Dropzone, a Flask extension that integrates Dropzone.js with Flask. For this issue, you can set DROPZONE_REDIRECT_VIEW to the view you want to redirect when uploading complete.


    Dropzone control the upload process, so you have to use Dropzone to redirect (make sure jQuery was loaded).
    Create an event listener, it will redirect page when all files in the queue finish uploading:

    <form action="{{ url_for('upload') }}" class="dropzone" id="my-dropzone" method="POST" enctype="multipart/form-data">
    </form>
    
    <script src="{{ url_for('static', filename='js/dropzone.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jquery.js') }}"></script>
    
    <script>
    Dropzone.autoDiscover = false;
    
    $(function() {
      var myDropzone = new Dropzone("#my-dropzone");
      myDropzone.on("queuecomplete", function(file) {
        // Called when all files in the queue finish uploading.
        window.location = "{{ url_for('upload') }}";
      });
    })
    </script>
    

    Handle the redirect in view function:

    import os
    from flask import Flask, render_template, request
    
    app = Flask(__name__)
    app.config['UPLOADED_PATH'] = os.getcwd() + '/upload'
    
    @app.route('/')
    def index():
        # render upload page
        return render_template('index.html')
    
    
    @app.route('/upload', methods=['GET', 'POST'])
    def upload():
        if request.method == 'POST':
            for f in request.files.getlist('file'):
                f.save(os.path.join(app.config['UPLOADED_PATH'], f.filename))
        return redirect(url_for('where to redirect'))
    
    0 讨论(0)
提交回复
热议问题