1. 程式人生 > >flask 檔案上傳和下載

flask 檔案上傳和下載

題外話:說真的,真心不會web框架,本來python學的就不怎麼樣。沒辦法,需要用到。比方說,有個使用者提交一個xlsx檔案,然後他要根據我的資料進行校驗,然後將校驗的資訊 ,‘正確’or‘不正確’新增到xlsx檔案中。由於他的資料比較多,大概1萬行左右,而我的校驗資訊行數為100萬行。

大前提:
雙方資料不能互相檢視(這種鬼設定,反正我們的資料一定不能給別人,然後別人說我的資料也不能給你們。尷尬,不然多簡單。我把資料給你,你自己搞。或者你資料給我,我自己搞,寫好再給你。)

還有。我不會加密python。混淆資料對於我這樣的資料還是能夠篩選的。

1).使用gui,我用python打包了一個exe,裡面包含了校驗資訊,然後給使用者用。(一定是提供工具給別人)。但是python的加密比較弱,我還沒試過用c來封裝。(其實那些資料我感覺也沒什麼用,而且誰有空破解我的渣渣程式,純粹是杞人憂天。沒辦法,組長要求。)

2).使用web ,我想試試flask ,這樣就能保證了我們的資料不外洩。做一個web端的,提供使用者上傳操作,然後我們根據上傳的檔案,將之處理。(這個和直接把資料給我有區別嗎?)為了做出區別,所以必須這樣,
這裡寫圖片描述
但這樣只是說明面上我們儲存你上傳的檔案,你可以刪除檔案。但是如果我偷偷的copy一份,你也不知道到。

3). 使用資料庫,但是如果你修改我給你的客戶端也一樣可以獲取其他資料。

不管這麼多了,先試試web端。可以藉此學習flask,何樂而不為呢?

目錄結構:
E:\———–web
| —–main.py
| —–templates
| ———- index.html

一:表單: ./templates/index.html
預設情況下: Flask 在templates 資料夾下找檔案。這和render_template(‘index.html’)有關,路徑當然也可以自定義。

index.html

<!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p
>
<input type=file name=file> <input type=submit value=Upload> </form>

./main.py 處理程式
這個程式不知道是哪個部落格抄過來的,忘了。感謝。

main.py

#encoding:utf8
from werkzeug.utils import secure_filename
from flask import Flask,render_template,jsonify,request,send_from_directory
import time
import os
import base64

app = Flask(__name__)
UPLOAD_FOLDER='upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
basedir = os.path.abspath(os.path.dirname(__file__))
ALLOWED_EXTENSIONS = set(['txt','png','jpg','xls','JPG','PNG','xlsx','gif','GIF'])

# 用於判斷檔案字尾
def allowed_file(filename):
    return '.' in filename and filename.rsplit('.',1)[1] in ALLOWED_EXTENSIONS

# 用於測試上傳,稍後用到
@app.route('/',methods=['GET'],strict_slashes=False)
def indexpage():
    return render_template('index.html')

# 上傳檔案
@app.route('/',methods=['POST'],strict_slashes=False)
def api_upload():
    file_dir = os.path.join(basedir, app.config['UPLOAD_FOLDER'])
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)
    f = request.files['file']  # 從表單的file欄位獲取檔案,file為該表單的name值

    if f and allowed_file(f.filename):  # 判斷是否是允許上傳的檔案型別
        fname = secure_filename(f.filename)
        print fname
        ext = fname.rsplit('.',1)[1]  # 獲取檔案字尾
        unix_time = int(time.time())
        # new_filename = str(unix_time)+'.'+ext  # 修改了上傳的檔名
        new_filename = '12'+'.'+ext  # 修改了上傳的檔名
        f.save(os.path.join(file_dir,new_filename))  #儲存檔案到upload目錄
        token = base64.b64encode(new_filename)
        print token

        return jsonify({"errno":0, "msg":"succeed ","token":token})
    else:
        return jsonify({"errno":1001, "errmsg":u"failed"})

if __name__ == '__main__':
    app.run(debug=True, port=9990)

這裡寫圖片描述
這裡寫圖片描述

目錄結構:
這裡寫圖片描述
效果圖:
主要作用:
上傳
下載
解析檔案
刪除檔案
這裡寫圖片描述

index.html:程式碼確實不行,不會html。

<!DOCTYPE html>
<html>
<head>


<title>檔案上傳和下載 </title>
<style>
html,body {margin:0px;padding:0px;height:100%}
.contain { width:100%;height:100%;margin:0px 0px 0px 0px; padding:1px ; border:0px solid #FF6600; text-align:center;background:url('../static/images/bg.png');background-size:100%}  
.inner_contain { width:80%; height:100px;margin:0px 0px 0px 120px ; border:0px solid #009966} 
.filebox { width:80%; height:500px;margin:0px 0px 0px 120px ; border:0px solid #009966;position:relative;color:#f3e9e9} 
.dirbox { width:100px; height:50px;margin:1px 1px 1px 0px; border:0px ;float:left;}
.imgdir{max-width:80%;max-height:80%}
.dirname{max-width:80%;max-height:10%;font-size:2px;font-weight:bold;margin:0px}

</style>
</head>

<body >
<div class="contain">  
    <div class="inner_contain">
    <p style=" font-size:50px ;margin:0px;color:#f3e9e9">資訊校驗</p>   
    </div>  

    <div class="inner_contain">
      <form  style=" font-size:20px ;margin:0px;color:#f3e9e9" action="{{ url_for('api_upload') }}" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form> 
    </div>   


     <div class="filebox">  
          {% if code==1 %}
           <p align="center" >上傳成功</p>
           {% endif %}{% if code==0 %}
           <p align="center">等待上傳</p>
           {% endif %}{% if code==2 %}
           <p align="center">上傳失敗</p>
           {% endif %}

       <table width="40%" border=0 style="font-size:15px;margin:0px 0px 0px 400px;color:#f3e9e9 ">
        <tr ><td>{% if alycode ==1%}處理中{% endif%}{% if alycode ==2 %}完成處理{% endif %}{% if alycode ==3 %}完成失敗{% endif %}</td><td align="right"><button type="button" ><a href= "{{ url_for('startAly') }}">生成檔案</a></button></td></tr>
       {% for x in allfileset[0] %}
        <tr>
        <td align="right">{{x}}</td>

        <td align="left"><button type="button"><a href="../static/upload/{{x}}" download="{{x}}">下載</a></button><button type="button" > <a href= "{{ url_for('deleteFile',filename=x) }}">刪除</a></button></p></td>
        </tr>
       {% endfor %}
       </table>  
    </div>
</div>  
</body>
</html>

有空重寫下,用了幾個模組都沒來的及總結。。。

# encoding:utf8
from werkzeug.utils import secure_filename
from flask import Flask, render_template, jsonify, request, send_from_directory, url_for,redirect
import time
import os
import sys
from aly import *

app = Flask(__name__)
UPLOAD_FOLDER = 'static/upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

dir = os.getcwd()
print dir
dir = os.path.join(dir, app.config['UPLOAD_FOLDER'])
print dir


alycode = 0
ALLOWED_EXTENSIONS = set(['txt', 'png', 'jpg', 'xls', 'JPG', 'PNG', 'xlsx', 'gif', 'GIF'])

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

def getAllFile(dir):
    dirset = []
    fileset = []
    for filename in os.listdir(dir):
        filepath = os.path.join(dir, filename)
        if os.path.isdir(filepath):
            filepath = filepath.split("\\")[-1]
            dirset.append(filepath)
        else:
            filepath = filepath.split("\\")[-1]
            fileset.append(filepath)

    return [fileset, dirset]



@app.route('/', methods=['GET','POST'], strict_slashes=False)
def api_upload():
    global alycode
    dir = os.getcwd()
    filedir = os.path.join(dir, app.config['UPLOAD_FOLDER'])
    allfileset = getAllFile(filedir)

    file_dir = os.path.join(dir, app.config['UPLOAD_FOLDER'])
    if not os.path.exists(file_dir):
        os.makedirs(file_dir)

    if  request.files.has_key('file'):

        try:
            f= request.files["file"]
            if f and allowed_file(f.filename):  # 判斷是否是允許上傳的檔案型別
                fname = secure_filename(f.filename)
                print fname
                ext = fname.rsplit('.', 1)[1]  # 獲取檔案字尾
                unix_time = int(time.time())
                # new_filename = str(unix_time)+'.'+ext  # 修改了上傳的檔名
                new_filename = 'upload' + '.' + ext  # 修改了上傳的檔名
                f.save(os.path.join(file_dir, new_filename))  # 儲存檔案到upload目錄
                # token = base64.b64encode(new_filename)
                # print token
                code = 1
                allfileset = getAllFile(filedir)

        except:
            code = 2

    else:
        code = 0
    return render_template('index.html', allfileset=allfileset, code=code, alycode=alycode)


@app.route('/aly', methods=['GET','POST'], strict_slashes=False)
def startAly():#不用管這個函式,則是處理上傳檔案的一個程式。
    global alycode
    try:
        t = Alydata()
        t.writeData()
        alycode =2
    except:
        alycode =3
    return redirect("/")

@app.route('/p/<filename>', methods=['GET','POST'], strict_slashes=False)
def deleteFile(filename):
    file = os.path.join(dir,filename)
    os.remove(file)

    return redirect("/")

if __name__ == '__main__':
    app.run(debug=True, port=9990)

處理的時候,會出現幾個異常,待完善。
就是這樣。
++++++++++++++++++++++++++++++++++++=

有空多看flask。實在菜雞呀。