簡體   English   中英

如何在不更改頁面的情況下上傳文件

[英]How to upload a file without changing the page

我想在服務器中上傳文件並對該文件執行操作。 我正在使用Flask渲染模板,該模板顯示用於選擇文件並使用后期操作上傳的表單。 我還使用websockets在服務器和客戶端之間進行通信。 我想做的是:

  1. 顯示index.html
  2. 用戶選擇一個文件
  3. 點擊提交按鈕
  4. 文件已上傳,但url保持不變,即它仍顯示index.html(它重定向到/ uploads)
  5. 使用websocket更改狀態

目前,正在發生的事情是python upload_file函數要求我返回諸如“文件已成功上傳”之類的內容,這正在改變視圖。 如果我從那里重定向到index.html,則會創建一個新會話。(我在這里可能是錯誤的)

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>

python文件的內容:

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)

你是對的。 每次重新加載頁面時,WebSocket連接都會關閉並再次重新打開。 為了擺脫這種情況,您必須使用會話cookie等對會話進行身份驗證。

但是您可以在python文件的upload_file -Method中編寫return('',204) 這告訴客戶端(瀏覽器)沒有內容。 然后可以在iFrame中實現“上傳”操作。

但我建議您使用DropzoneJS

Flask的示例:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM