python flask图片文件二进制流上传和接收

NO.1
flask接收二进制流图片文件

图片二进制流上传

服务端代码

@app.route('/upFile',methods=["POST"])
def upFile():
  imgName=""
  # 接收二进制文件流图片
  uploaded_file = request.files['file']
  if uploaded_file.filename != '':
    filename = request.form['filename']
    print('filename',filename)
    uploaded_file.save("./"+filename)
    return {
      "code":200,
      "data":filename,
      "msg":"test"
    }

小程序上传代码

wx.uploadFile({
  url: "https://xxx.com/upFile",
  filePath: filePath,
  name: "file",
  formData: {
    filename: "xxx.png",
  },
  success(res) {
    const data = res.data;
    console.log(`上传文件流成功`, res);
  },
  fail: (err) => {
    console.log(`上传文件流失败`, err);
  },
});
NO.2
flask返回二进制流图片文件

Snipaste_2022-05-21_15-56-43

服务端代码

from flask import send_file
@app.route('/getFile', methods=['GET'])
def get_file():
    filename = request.args.get("filename")
    print("filename",filename)
    filePath="./"+filename
    return send_file(filePath)

微信小程序

wx.downloadFile({
  url: `https://xxx.com/getFile?filename=${filename}`, 
  success(res) {
    console.log(`文件下载成功`, res,res.tempFilePath);
  },
  fail: (err) => {
    console.log(`文件下载失败`, err);
  },
});
NO.3
Tips

图片使用base64

  1. 图片转base64体积会增加33.3%左右

  2. img标签使用base64,字节太大时渲染会影响性能

END.