LoginSignup
53
56

More than 5 years have passed since last update.

Railsで、画像をアップロード、ダウンロードするREST API

Last updated at Posted at 2014-04-19

たくさんの方が書かれてる内容ではありますが、備忘録として書いておきますネ
RESTfulじゃない!とかRails wayじゃない!とか是非ツッコミください。

特に追加するgemは無いです。

Model

画像データとstringのタグを持つImage Modelを作ります。

$ rails g model Image tag:string data:binary
$ rake db:migrate

Routes

こんな感じのルートを定義してみました。
dataは空のままPOSTして、その後Request Bodyにバイナリを直接突っ込んでPUTでアップロードするという使い方です。

routes.rb
get 'images/:id' => 'images#show'
post 'images' => 'images#create'

get 'images/:id/download' => 'images#download'
put 'images/:id/upload' => 'images#upload'

Controller

$ rails g controller Images
images_controller.rb
class ImagesController < ApplicationController
  def show
    image = Image.find(params[:id])
    render json: image, except: [:data]
  end

  def create
    image = Image.new
    image.tag = params[:tag]
    image.save!
    render json: image, except: [:data]
  end

  def download
    image = Image.find(params[:id])
    send_data image.data, type: "image/png", disposition: 'inline'
  end

  def upload
    image = Image.find(params[:id])
    image.data = request.raw_post
    image.save!
    render json: image, except: [:data]
  end
end

curlで試す

$ rails s
$ curl --request POST -H 'Content-Type: application/json' -d '{"tag":"trumpet"}' http://localhost:3000/images
$ curl --request PUT -H 'Content-Type: application/octet-stream' --data-binary "@icon.png" http://localhost:3000/images/1/upload
$ curl http://localhost:3000/images/1/download > icon_downloaded.png

さすがrails, お手軽です。
REST APIのバックエンド作るだけならもっとシンプルなsinatraとか使った方が良いかもしれませんが・・・

53
56
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
53
56