Skip to content

Instantly share code, notes, and snippets.

@ocadaruma
Created April 19, 2014 10:32
Show Gist options
  • Save ocadaruma/11080626 to your computer and use it in GitHub Desktop.
Save ocadaruma/11080626 to your computer and use it in GitHub Desktop.
Railsで、画像をアップロード、ダウンロードするREST API ref: http://qiita.com/ocadaruma/items/d12a80f7dbe07dd851a4
$ rails g model Image tag:string data:binary
$ rake db:migrate
$ rails g controller Images
$ 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
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
get 'images/:id' => 'images#show'
post 'images' => 'images#create'
get 'images/:id/download' => 'images#download'
put 'images/:id/upload' => 'images#upload'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment