Last active
March 3, 2020 17:35
-
-
Save skycocker/6d04e4cc9a5f5af66dbebd884a0b4718 to your computer and use it in GitHub Desktop.
Uploading images to a Rails API using Paperclip (via either base64 string-encoded image or a public HTTP image URL)
This file contains hidden or 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
module ImageUploadable | |
extend ActiveSupport::Concern | |
private | |
def set_image_by_params_for(model, params) | |
image_uri = params[:image_uri] | |
image_base64 = params[:image_base64] | |
set_image_from_uri_for(model, image_uri) if image_uri.present? | |
set_image_from_base64_for(model, image_base64) if image_base64.present? | |
end | |
def set_image_from_uri_for(model, image_uri) | |
model.image = URI.parse(image_uri) | |
end | |
def set_image_from_base64_for(model, image_base64) | |
tempfile = Tempfile.new(tempfile_name_for(model)) | |
tempfile.binmode | |
tempfile.write(Base64.decode64(image_base64)) | |
tempfile.rewind | |
model.image = tempfile | |
ensure | |
tempfile.close | |
tempfile.unlink | |
end | |
def tempfile_name_for(model) | |
@image_tempfile_name ||= begin | |
millisecond_timestamp = (Time.now.to_f * 10000).to_i | |
"#{model.class.name}_image_#{millisecond_timestamp}" | |
end | |
end | |
end |
This file contains hidden or 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
# example usage | |
class UsersController < ApiController | |
include ImageUploadable | |
def update | |
user = User.find(params[:id]) | |
user.assign_attributes(user_params) | |
set_image_by_params_for(user, params[:user]) | |
if user.save | |
render json: user, status: :ok | |
else | |
render json: { errors: user.errors }, status: :unprocessable_entity | |
end | |
end | |
private | |
def user_params | |
params.require(:user).permit(:email, :name) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment