flask框架上传文件思路过程以及代码解析

import os
import uuid

from PIL import Image
from flask import Flask, render_template, request
from flask_bootstrap import Bootstrap
from flask_script import Manager

app=Flask(__name__)
manager=Manager(app)
Bootstrap(app)
app.config['SECRET_KEY']='sadasd'
ALLOWED_SUFFIX=['jpg','jpeg','png']
def suoxiao(path,prefix='s_',width=200,height=200):
    img=Image.open(path)
    img.thumbnail((width,height))
    pathInfo=os.path.split(path)
    newname=prefix+pathInfo[-1]
    img.save(os.path.join(pathInfo[0],newname))
    print('sssssssssssssss',pathInfo,path,newname,pathInfo[0],pathInfo[1])
    return pathInfo


def makename():
    name=uuid.uuid4()
    return  name

#思路
#表单页面当提交了图片文件之后,来到后端处理,先看他的后缀,看一下是不是符合我们要求的后缀,一旦匹配成功,那么这个文件是及合法,现在给他起名字存在我们服务器端,
#名字涉及到唯一性,在此我们用到了uuid,我们起好了这么唯一的字符串后,将这个图片文件存在拼接的目录 getcwd(),'static/upload'+唯一的新名字+'.'+'后缀',
#这里面,然后获得将路径拼接一下path通过接口传到前端,通过<img src="{{'url_for('static',filename=path)'}}">
@app.route('/',methods=['GET','POST'])
def index():
    #如果表单提交了并且提交了文件而不是为空
    if request.method=='POST' and  request.files.get('file'):
        file=request.files.get("file")
        filename=file.filename
        print(filename)#b.jpg
        print(file)#<FileStorage: '显卡排名.jpg' ('image/jpeg')>
        #获得了照片文件,要看一下是不是符合规范
        houzhui=filename.split('.')[-1]
        print(houzhui)  # jpg
        if houzhui in ALLOWED_SUFFIX:
            newname=str(makename())
            print(os.getcwd())
            print(newname) #358b9ab8-f8cf-4639-90c5-5ef04621a414
            print(os.path.join(os.getcwd(),'static/upload/'+newname+'.'+houzhui))
            allname=os.path.join(os.getcwd(),'static/upload/'+newname+'.'+houzhui)
            #/home/yc/Desktop/flask/static/upload/c8ddfb49-9ed3-48e4-8a00-0fe65e5b7a61.jpg
            file.save(os.path.join(os.getcwd(),'static/upload/'+newname+'.'+houzhui))
            path=os.path.join('upload/'+newname+'.'+houzhui)
            print(path)

            #upload/c8ddfb49-9ed3-48e4-8a00-0fe65e5b7a61.jpg
            suoxiao(allname)
            return render_template('upload1.html',path=path)
    return render_template('upload1.html')

if __name__=='__main__':
    manager.run()
{% extends 'common/base.html' %}
{% block pagecontent%}
    <h2>文件上传</h2>

    <form action="" method="post" enctype="multipart/form-data">
    {{ path }}
    <img src="{{ url_for('static',filename=path) }}">
    <input type="file" name="file" ><br>
    <input type="submit" value="upload">
    </form>
{% endblock %}

猜你喜欢

转载自blog.csdn.net/XYLHxylh/article/details/83033819