[PYTHON] Image upload function with Vue.js + Flask

Overview

This time, we will create an image recognition application that uses Vue.js for the front end and Flask for the back end. For the time being, this time we will implement the image upload function.

environment

The environment was built in the above environment. See the links below for instructions and details.

Vue + Flask on Docker

Explanation of key points

Vue The following code explains the details.

Home.vue


//Upload image to server
    onUploadImage () {
      var params = new FormData()
      params.append('image', this.uploadedImage)
      //I am posting the data converted to FormData using Axios to Flask.
      axios.post(`${API_URL}/classification`, params).then(function (response) {
        console.log(response)
    })
  1. The acquired image is Base64-converted. "Data: image / jpeg: base64, ~"
  2. With FormData, data is converted to "key: value" format by HTTP request.
  3. Apply Axios and send data with '127 .0.0.1: 5000 / classification' + POST method.

Flask

The following code explains the details.

app.py


@app.route('/classification', methods=['POST'])
def uploadImage():
    if request.method == 'POST':
        base64_png =  request.form['image']
        code = base64.b64decode(base64_png.split(',')[1]) 
        image_decoded = Image.open(BytesIO(code))
        image_decoded.save(Path(app.config['UPLOAD_FOLDER']) / 'image.png')
        return make_response(jsonify({'result': 'success'}))
    else: 
        return make_response(jsonify({'result': 'invalid method'}), 400)
  1. "data: image / jpeg: base64, ~" exists inside FormData. Get the file name.
  2. Get an image with Pillow (PIL).
  3. Save the image.

Overall picture

Vue

Home.vue


<template>
  <div>
    <div class="imgContent">
      <div class="imagePreview">
        <img :src="uploadedImage" style="width:100%;" />
      </div>
      <input type="file" class="file_input" name="photo" @change="onFileChange"  accept="image/*" />
      <button @click='onUploadImage'>Please judge the image ...</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

const API_URL = 'http://127.0.0.1:5000'
export default {
  data () {
    return {
      uploadedImage: ''
    }
  },
  methods: {
    //Reflect the selected image
    onFileChange (e) {
      let files = e.target.files || e.dataTransfer.files
      this.createImage(files[0])
    },
    //View uploaded image
    createImage (file) {
      let reader = new FileReader()
      reader.onload = (e) => {
        this.uploadedImage = e.target.result
      }
      reader.readAsDataURL(file)
    },
    //Upload image to server
    onUploadImage () {
      var params = new FormData()
      params.append('image', this.uploadedImage)
      //I am posting the data converted to FormData using Axios to Flask.
      axios.post(`${API_URL}/classification`, params).then(function (response) {
        console.log(response)
      })
    }
  }
}
</script>

Flask

Points to remember

--CORS allows resources to be shared by different origins (protocols, domains, ports). --CORS is required if you have different web applications. --Japanese is supported by app.config ['JSON_AS_ASCII'] = False.

app.py


# render_template: Specify the template to refer to
#jsonify: json output
from flask import Flask, render_template, jsonify, request, make_response

#CORS: Library for Ajax communication
from flask_restful import Api, Resource
from flask_cors import CORS 
from random import *
from PIL import Image
from pathlib import Path
from io import BytesIO
import base64

# static_folder: Specify the path of the static file built with vue
# template_folder: index built with vue.Specify html path
app = Flask(__name__, static_folder = "./../frontend/dist/static", template_folder="./../frontend/dist")

#Japanese
app.config['JSON_AS_ASCII'] = False
#CORS=Terms for secure communication with Ajax
api = Api(app)
CORS(app)

UPLOAD_FOLDER = './uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

#Index when receiving any request.See html
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def index(path):
    return render_template("index.html")

@app.route('/classification', methods=['POST'])
def uploadImage():
    if request.method == 'POST':
        base64_png =  request.form['image']
        code = base64.b64decode(base64_png.split(',')[1]) 
        image_decoded = Image.open(BytesIO(code))
        image_decoded.save(Path(app.config['UPLOAD_FOLDER']) / 'image.png')
        return make_response(jsonify({'result': 'success'}))
    else: 
        return make_response(jsonify({'result': 'invalid method'}), 400)

# app.run(host, port): Start flask server by specifying host and port
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

State

スクリーンショット 2020-07-29 18.47.42.png

Like this

It was very helpful

https://developer.mozilla.org/ja/docs/Web/HTTP/CORS POST image, face detection, draw on face with canvas

Recommended Posts

Image upload function with Vue.js + Flask
Image upload & customization with django-ckeditor
File upload with Flask + jQuery
Vue.js + Flask environment construction memorandum ~ with Anaconda3 ~
How to upload with Heroku, Flask, Python, Git (4)
Resize multipart.File type image with golang ~ Upload to S3
Image processing with MyHDL
Image recognition with keras
How to upload with Heroku, Flask, Python, Git (Part 3)
How to upload with Heroku, Flask, Python, Git (Part 1)
[Django] Implement image file upload function without using model
IP restrictions with Flask
Image processing with Python
POST the image with json and receive it with flask
Hello world with flask
Programming with Python Flask
Image uploader in Flask
Image Processing with PIL
Twitter posting client made with Flask with simple login function
[With image diagram] Nginx + gunicorn + Flask converted to Docker [Part 2]
[With image diagram] Nginx + gunicorn + Flask converted to Docker [Part 1]
Image download with Flickr API
Try function optimization with Optuna
Implement login function with django-allauth
Read image coordinates with Python-matplotlib
Image processing with PIL (Pillow)
Touch Flask + run with Heroku
Hello World with Flask + Hamlish
Approximate sin function with TensorFlow
Image editing with python OpenCV
Unit test flask with pytest
API with Flask + uWSGI + Nginx
Web application development with Flask
Sorting image files with Python (3)
Create Image Viewer with Tkinter
Sorting image files with Python
Image caption generation with Chainer
View flask coverage with pytest-cov
Get image features with OpenCV
Zura with softmax function implemented
Django REST framework with Vue.js
Upload multiple files in Flask
Image recognition with Keras + OpenCV
[Python] Image processing with scikit-image
[Python] I made an image viewer with a simple sorting function.
Image upload & download to Azure Storage. With Python + requests + REST API
I tried to make an image similarity function with Python + OpenCV