简体   繁体   中英

How to upload a file without changing the page

I want to upload a file in server and perform operation on that file. I am using Flask to render a template which shows a form to select a file and upload using post operation. I am also using websockets to communicate between server and client. What i want to do is:

  1. Show index.html
  2. User selects a file
  3. Click on submit button
  4. File is uploaded but url doesn't change ie it still shows index.html (it redirects to /uploads)
  5. Status is changed using websockets

Currently, what's happening is the python upload_file function requires me to return something like "File uploaded successfully" which is changing view. If i redirect to the index.html from there, a new session is created.(I may be wrong here)

Contents of index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Flask SocketIO Test</title>
</head>
<body>
<p>Anacall</p>

<form action="/upload" method="POST"
      enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit"/>
</form>

<br>
<p id="status">Status</p>

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/socket.io/1.3.6/socket.io.min.js"></script>
<script type="text/javascript" charset="utf-8">
        var socket = io.connect('http://' + document.domain + ':' + location.port);

         socket.on('connect', function() {
            socket.emit('get_status')
            console.log('Websocket connected!');
            });

        socket.on('response_status',function(){
        document.getElementById("status").innerHTML = "Status : File Status";
        console.log("response received");
    });



</script>
</body>
</html>

Contents of python file:

from flask import Flask, render_template, request, redirect, url_for
from flask_socketio import SocketIO, emit
from werkzeug import secure_filename

app = Flask(__name__)
socketio = SocketIO(app)

UPLOAD_FOLDER = '/static'
ALLOWED_EXTENSIONS = set(['xlsx', 'txt'])

status = None


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


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


@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        if 'file' not in request.files:
            return 'No file selected'
        file = request.files['file']
        if file.filename == '':
            return "No file selected"
        if file and allowed_file(file.filename):
            file.save(secure_filename("file.xlsx"))  # saves in current directory
            status = "File uploaded"

    return redirect(url_for('index'))


@socketio.on('get_status')
def send_status():
    print("Send status now")
    if (status != None):
        emit("response_status")


if __name__ == '__main__':
    socketio.run(app, host='10.131.65.115', port=12000)

You are right. Every time when you are reloading a page, the WebSocket-connection is closed and reopened again. To get rid of this you have to authenticate the session with session-cookies etc.

But you could just write return ('', 204) in the upload_file -Method of your python-file. This tells the client (Browser) that there is no content. The "upload"-Operation could than be realized within an iFrame.

But I would recommend you the use of DropzoneJS .

Examples with Flask:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM