Carrierwave Uploader Not Including Model.id in Path

Photo by Maarten van den Heuvel on Unsplash

A file can be uploaded to server in two ways, one we can transport the image as base64 string as plain text and another i is using multipart/form-data .

The first i is the worst idea as it sends the entire image as plain text. While the later ane multipart is preferable way to transport file every bit it ship the epitome information byte past byte.

In Rails, we have few prominent precious stone Carrierwave , Paperclip , Dragonfly, etc, to implement this concept.

Why Carrierwave?

Nosotros go with Carrierwave as it uncomplicated and flexible to configure and include in Rails. Information technology has a lot more flexibility and it doesn't clutter your models with configuration.Y'all can ascertain uploader classes instead. It allows you to easily reuse, extend etc your upload configuration.

Through this commodity, allow'southward try the single and multiple file upload using Carrierwave.

Single File Upload

Lets create a track api project,

          runway new case— api        

Include carrierwave precious stone into our precious stone file

jewel 'carrierwave' and do bundle install

Now we can endeavor to create an api for user creation with user image.

Generate a controller and model for User api

          rail grand scaffold User name:string email:string
track db:migrate

Configure model for file upload

First we need to generate carrierwave uploader for our user_image with following command

          rails chiliad uploader user_image        

This command volition create uploader file for user_image app/uploaders/user_image_uploader.rb

Carrierwave will shop the file in the in a higher place configure store_dir path with filename . We can also filter the file types during upload by whitelisting the extension.

Now nosotros demand to configure this Uploader to our model file.

For that nosotros need to add new cavalcade to our user schema to shop filename,

          rails g migration add_filename_to_users user_image:string
rail db:migrate

And configure the uploader to the user model as beneath,

          course User < ActiveRecord::Base
mount_uploader : user_image , UserImageUploader
finish

Add Api param to receive file

Add together this new param, user_image in controller to receive the image file

          class Api::V1::UsersController < ApplicationController          def create
@user = User.new(user_params)
if @user.save
render json: {msg: ' The prototype is successfully uploaded!!'}
else
render json: {user: @user.errors},status:unprocessable_entity
finish
stop
def user_params
params.let(:proper name, :electronic mail, : user_image )
end
stop

Verify Epitome upload api

Now we can starting time the server runway s and verify the api by uploading an image

          curl -X POST \
> http://localhost:3000/users \
-F email=testing@gmail.com \
-F name=test \
-F user_image=@/home/firose/Downloads/photo_2019-xi-11_11-fifty-40

This volition do two things,

  • Store the file equally per the configuration in Uploader file, and

  • Salve the filename in the created user data.

Additional to the filename we can also store other file information like file_size, content type,etc by adding method and before relieve callback method.

          class User < ApplicationRecord
mount_uploader :user_image, UserImageUploader
before_save :update_avatar_objects
def update_image_file_objects
if image_file.present?
cocky.image_file_content_type = image_file.content_type
cocky.image_file_file_size = image_file.file.size
end
end
end

Multiple Files Upload

Now, we can effort for multiple file uploads. It is just like the unmarried file upload with slight changes

In model file we take to alter mount_uploader equally mount_uploaders

          class User < ActiveRecord::Base of operations
mount_uploaders :user_image, UserImageUploader
end

update the file param in the controller to receive multiple file, i.due east, the exiting param user_image will be inverse every bit {user_image: []}

          class Api::V1::UsersController < ApplicationController          def create
@user = User.new(user_params)
if @user.save
render json: {msg: ' The epitome is sucessfully uploaded!!'}
else
render json: {user: @user.errors},status:unprocessable_entity
finish
end
def user_params
params.permit(:name, :electronic mail, {user_image: []})
end
terminate

Verify for multiple file

Lets check it by uploading 2 files

          curl -X POST \
http://localhost:3000/users \
-F email=testing@gmail.com \
-F name=test \
-F 'user_image[]=@/home/firose/Downloads/pic1.jpg' \
-F 'user_image[]=@/dwelling/firose/Downloads/picture.jpg'

We can run across both Images are stored to the path

We can discover the filename column have array string containing both the prototype files.

Francium Tech is a technology visitor laser focused on delivering top quality software of scale at extreme speeds. Numbers and Size of the data don't scare us. If you lot have whatsoever requirements or want a free wellness bank check of your systems or architecture, feel gratis to shoot an email to contact@francium.tech , we will arrive impact with you lot!

mcgregorexperwas.blogspot.com

Source: https://blog.francium.tech/upload-multiple-files-in-rails-api-using-carrierwave-1f37aaad2b07

0 Response to "Carrierwave Uploader Not Including Model.id in Path"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel