flask實現客戶端上傳圖片與base64編碼轉換
參考鏈接:https://blog.csdn.net/weixin_36380516/article/details/80347192
測試代碼:
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# Author: elfin-2020
# project: ImgPushWeb
import os
import sys
import base64
import socket
from flask import Flask, request, jsonify, render_template
sys.path.append(os.path.abspath(__file__).split("Img2Web")[0])
path_dir = os.path.dirname(os.path.abspath(__file__))
hostname = socket.gethostname()
ip_dir = socket.gethostbyname(hostname)
ALLOWED_EXTENSIONS = {'png', 'PNG'}
def allowed_file(filename):
return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS
def set_app():
# 初始化Flask對象
#####################################################
app = Flask(__name__, template_folder='../templates')
# 設置前端中文不亂碼
app.config["JSON_AS_ASCII"] = False
#####################################################
@app.route("/img", methods=["GET"])
def web_load():
return render_template("admin.html")
@app.route("/img", methods=["POST"])
def img_pull():
res_dict = {
"code": 0,
"msg": "執行失敗",
"data": {},
}
file = request.files.get("img")
img_base64 = request.form.get("base64")
if not file:
res_dict["msg"] = "沒有上傳圖片"
return jsonify(res_dict)
if not allowed_file(file.filename):
res_dict["msg"] = "請上傳png/PNG格式的圖片"
return jsonify(res_dict)
# 將圖片轉為base64編碼
#################################################
# 獲取圖片文件對象的數據流
img_stream = file.stream.read()
img_base64 = base64.b64encode(img_stream)
#################################################
res_dict["code"] = 1
res_dict["msg"] = "執行成功"
res_dict["data"]["img_stream"] = str(img_base64)
print(dir(file.stream))
return jsonify(res_dict)
app.run(host=ip_dir, port=10018, debug=True)
if __name__ == '__main__':
set_app()