flask 文件上传和下载

先给大神链接:https://zhuanlan.zhihu.com/p/24423891
其他一些参考:http://flask.pocoo.org/docs/0.10/patterns/fileuploads/
http://blog.csdn.net/grief_of_the_nazgul/article/details/50952003

题外话:说真的,真心不会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。实在菜鸡呀。

  • 11
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值