溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python實現(xiàn)文件上傳界面的方法

發(fā)布時間:2020-09-03 14:23:16 來源:億速云 閱讀:273 作者:小新 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)python實現(xiàn)文件上傳界面的方法,小編覺得挺實用的,因此分享給大家做個參考,希望大家閱讀完這篇文章后可以有所收獲。

本文章代碼上傳在碼云上

代碼地址

git@gitee.com:DanYuJie/upanddown.git

這里我們使用flask框架,簡單實用

目錄結(jié)構(gòu):
upandown/
    static/
        css/
        js/
            jquery.min.js
            toastr.min.js
    templates/
            index.html
    test.py

首先我們需要一個頁面在templates/index.html(這里使用form表單實現(xiàn))

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="../static/css/toastr.min.css">
    <script src="../static/js/jquery.min.js"></script>
    <script src="../static/js/toastr.min.js"></script>
    <title>Document</title>
</head>
<body>
    <form method="POST" action="/upload" enctype="multipart/form-data">
        <input type="file" name="file" id="file">
        <input type="submit" value="upload">
        <a href=""></a>
    </form><hr>
    <ol id="filelist">
    </ol>
    <script>
        function checkstatus(){
            if('{{status}}'== 'OK'){
                toastr['success']("上傳成功");
            }else if('{{status}}'== 'null'){
                toastr['error']("上傳失敗");           
            }
        }
        function get_list(){
            $.ajax({
                url:'/getlist',
                type:'GET',
                success:function(result){
                    len_result = result.length;
                    for(var x =0; x < len_result; x++){
                        $("#filelist").append('<br><a href=/download/' + result[x] + '>' + result[x] 
                        +'</a>');
                    }
                    alert(content_list);
                },
                error:function(){
                    alert("失敗");
                }
            });
        }
    checkstatus();
    get_list();
    </script>
</body>
</html>

然后是后臺接收

test.py

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask,render_template, request, send_from_directory,jsonify, redirect
import os
# import sys
# reload(sys)
# sys.setdefaultencoding('utf-8')
app = Flask(__name__)
# ALLOWED_EXTENSTIONS = set(['png', 'jpg', 'jpeg', 'gif'])
app.config['UPLOAD_FOLDER'] = os.getcwd()
download_floder = app.config['UPLOAD_FOLDER'] + '/upload'
def allow_file(filename):
    allow_list = ['png', 'PNG', 'jpg', 'doc', 'docx', 'txt', 'pdf', 'PDF', 'xls', 'rar', 'exe', 'md', 'zip'] 
    a = filename.split('.')[1]
    if a in allow_list:
        return True
    else:
        return False
@app.route('/main')
def home():
    return render_template('index.html')
@app.route('/getlist')
def getlist():
    file_url_list = []
    file_floder = app.config['UPLOAD_FOLDER'] + '/upload'
    file_list = os.listdir(file_floder)
    for filename in file_list:
        file_url = url_for('download',filename=filename)
        file_url_list.append(file_url)
    # print file_list
    return jsonify(file_list)
@app.route('/download/<filename>')
def download(filename):
    return send_from_directory(download_floder,filename, as_attachment=True)
@app.route('/upload', methods=['POST', 'GET'])
def upload():
    file = request.files['file']
    if not file:
        return render_template('index.html', status='null')
    # print type(file)
    if allow_file(file.filename):
        file.save(os.path.join(app.config['UPLOAD_FOLDER']+'/upload/', file.filename))
        return render_template('index.html', status='OK')
    else:
        return 'NO'
if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

關(guān)于python實現(xiàn)文件上傳界面的方法就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI