7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

javascript/canvas/axiosで画像をPOSTしてpython/flaskで画像を受け取る

Posted at

メモ

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(',')を使っている

7
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?