Created
April 19, 2014 10:32
-
-
Save ocadaruma/11080626 to your computer and use it in GitHub Desktop.
Railsで、画像をアップロード、ダウンロードするREST API ref: http://qiita.com/ocadaruma/items/d12a80f7dbe07dd851a4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ rails g model Image tag:string data:binary | |
$ rake db:migrate |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ rails g controller Images |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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