LoginSignup
4
2

More than 5 years have passed since last update.

Falconで画像アップロードを爆速開発

Last updated at Posted at 2018-03-31

クライアントサイド

jQueryを使いContent-Type: multipart/form-dataで画像を送ります。
アップロードボタンを押せば、canvasに表示されている画像をアップロードできます。

client.js
$('#upload').click(function(){
  // アップロードボタンをdisableにする
  $('#upload').prop('disabled', true);
  $('#upload').text('Wait...');

  // canvasからbase64画像データを取得
  var base64 = $('#canvas').get(0).toDataURL('image/jpeg');        
  // base64からBlobデータを作成
  var barr, bin, i, len;
  bin = atob(base64.split('base64,')[1]);
  len = bin.length;
  barr = new Uint8Array(len);
  i = 0;
  while (i < len) {
    barr[i] = bin.charCodeAt(i);
    i++;
  }
  blob = new Blob([barr], {type: 'image/jpeg'});

  // フォームデータの形に整形し画像を添付
  var fd = new FormData();
  fd.append('file', blob);
  $.ajax({
    url: API_ENDPOINT, // http://xxx.xxx.xxx.xxx
    type: 'POST',
    dataType: 'json',
    data: fd,
    processData: false,
    contentType: false
  })
  .done(function( res, textStatus, jqXHR ) {
    console.log(res.result);
  });
});

サーバサイド

必要なものをインストール

pip install falcon
pip install falcon-multipart
pip gunicorn

# gunicornは, apt-getでインストールした/usr/bin/gunicornと競合する可能性があります. 
# その場合, sudo apt-get remove gunicornで消し、シンボリックリンクを張って解決します.
# sudo ln -nsf /home/hogehoge/.pyenv/shims/gunicorn /usr/bin/gunicorn

FalconでPOSTを受け取り画像をサーバに保存します。

server.py
# -*- coding: utf-8 -*-
import falcon
from falcon_multipart.middleware import MultipartMiddleware
import json
from datetime import datetime

class CORSMiddleware:
    def process_request(self, req, resp):
        resp.set_header('Access-Control-Allow-Origin', '*')

class Upload:
  def on_post(self, req, res):

    image = req.get_param('file')
    raw = image.file.read()
    filepath = './' + datetime.now().strftime('%Y%m%d%H%M%S') + '.jpg'
    with open(filepath, 'wb') as f:
      f.write(raw)

    resp = {
      'result': filepath + ' uploaded',
    }
    res.body = json.dumps(resp)

api = falcon.API(middleware=[CORSMiddleware(), MultipartMiddleware()])
api.add_route('/', Upload())

falconの動かし方

gunicorn server:api -b 192.168.xxx.xxx  # IPを指定してください.

以上でブラウザから画像をサーバにアップロードできます!!!!!!

4
2
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
4
2