flask框架上傳檔案思路過程以及程式碼解析
阿新 • • 發佈:2018-12-15
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 %}