1. 方式一:后端传送base64编码后的图片
-
后端python代码
# 前端访问接口/image?skuid=999999
@app.route("/image", methods = ["get"])
def sendImage():
skuid = request.args.get('skuid')
img_stream = ''
img_local_path = "./templates/images/" + skuid + "..jpg" # 准备发送给前端图片的路径
with open(img_local_path, 'rb') as img_f:
img_stream = img_f.read()
img_stream = base64.b64encode(img_stream)
return img_stream
-
前端js代码
//请求图片
const commodity_image = document.createElement("img");
let image_request = new XMLHttpRequest();
let imageURL="/image?skuid=" + r[j]["skuid"]; //r[j]["skuid"]为get请求参数skuid的值
image_request.open("GET", imageURL);
image_request.send();
//服务端返回图片的base64编码后将其以图片方式展示到界面上(在返回的编码前面加上"data:image/jpeg;base64,"即可)
image_request.onload = function () {
let image_r = image_request.response;
let imageSRC = "data:image/jpeg;base64," + image_r;
commodity_image.src = imageSRC
}
//然后把commodity_image加到网页的 Document 对象中即可
-
前端图片的src
这种方式前端图片的src将会是一大串编码(即data:image/jpeg;base64,加上图片的base64编码)
2. 方式二:后端传送base64编码后的图片(优)
-
后端python代码
from flask import make_response
@app.route("/image", methods = ["get"])
def sendImage():
skuid = request.args.get('skuid')
img_local_path = "./templates/images/" + skuid + "..jpg"
img_f = open(img_local_path, 'rb')
res = make_response(img_f.read()) # 用flask提供的make_response 方法来自定义自己的response对象
res.headers['Content-Type'] = 'image/jpg' # 设置response对象的请求头属性'Content-Type'为图片格式
img_f.close()
return res
-
前端js代码
const commodity_image = document.createElement("img");
let imageURL="/image?skuid=" + r[j]["skuid"];
commodity_image.src = imageURL;
-
前端图片的src