メモ
Javascript側(抜粋)
const canvas = this.$refs.imageLayer;
const base64_png = canvas.toDataURL("image/png");
const fd = new FormData();
fd.append("image", base64_png);
const BASE_URL = "http://127.0.0.1:5000";
axios
.post(BASE_URL, fd)
.then(function (response) {
console.log("response", response);
})
.catch(function (error) {
console.log(error);
});
Python(Flask)側
import os
from flask import Flask, make_response, request
from flask_cors import CORS
from pathlib import Path
import base64
from PIL import Image
from io import BytesIO
app = Flask(__name__)
CORS(app)
@app.route('/', methods=['POST'])
def send():
if request.method != 'POST':
return make_response(jsonify({'result': 'invalid method'}), 400)
base64_png = request.form['image']
code = base64.b64decode(base64_png.split(',')[1]) # remove header
image_decoded = Image.open(BytesIO(code))
image_decoded.save(Path(app.config['UPLOAD_FOLDER']) / 'image.png')
return make_response(jsonify({'result': 'success'}))
base64のデータにdata:image/png;base64,kpvdfkg...
のような形でヘッダっぽいものがついてくるので,split(',')
を使っている