接下來給搭建講解Flask如何接受圖片文件,上面是複雜寫法,下面是簡單寫法。
思路整理:接收圖片->定義一個圖片存放的位置->給圖片重命名(爲了唯一性)->保存操作->返回狀態
下面是複雜的寫法:
basedir = os.path.abspath(os.path.dirname(__file__)) #定義一個根目錄 用於保存圖片用
import os,sys,random,string
from app import app,request,json,url_for
@app.route('/api/v1/ckeditorUpload',methods=['GET','POST'])
def editorData():
#生成隨機字符串,防止圖片名字重複
ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 16))
#獲取圖片文件 name = upload
img = request.files.get('upload')
#定義一個圖片存放的位置 存放在static下面
path = basedir+"/static/img/"
#圖片名稱 給圖片重命名 爲了圖片名稱的唯一性
imgName = ran_str+img.filename
#圖片path和名稱組成圖片的保存路徑
file_path = path+imgName
#保存圖片
img.save(file_path)
#這個是圖片的訪問路徑,需返回前端(可有可無)
url = '/static/img/'+imgName
#返回圖片路徑 到前端
return url
思路:接收圖片 ->定義保存路徑->獲取名稱->保存操作
下面是簡單寫法:
basedir = os.path.abspath(os.path.dirname(__file__)) #定義一個根目錄 用於保存圖片用
from app import app,request
@app.route('/api/v1/ckeditorUpload',methods=['GET','POST'])
def editorData():
#獲取圖片文件 name = upload
img = request.files.get('upload')
#定義一個圖片存放的位置 存放在static下面
path = basedir+"/static/img/"
#圖片名稱
imgName = img.filename
#圖片path和名稱組成圖片的保存路徑
file_path = path+imgName
#保存圖片
img.save(file_path)
#url是圖片的路徑
url = '/static/img/'+imgName
return url
不懂留言交流