Fix product images
This commit is contained in:
@@ -68,10 +68,10 @@ module Suppliers
|
||||
respond_to do |format|
|
||||
if @product.update_attributes(product_params)
|
||||
format.html { redirect_to [:suppliers, :products], notice: t('action.update.successfull', model: Product.model_name.human) }
|
||||
format.json { render json: @product }
|
||||
format.json { render json_response @product }
|
||||
else
|
||||
format.html { render action: "edit" }
|
||||
format.json { render json: {errors: @product.errors}, status: :unprocessable_entity }
|
||||
format.json { render json_response @product }
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -96,11 +96,34 @@ module Suppliers
|
||||
def product_params
|
||||
permitted_attributes = [:name, :code, :price, :description, :image, :visible, :position, :active, :product_category_id]
|
||||
# do not raise in development and test for json communication
|
||||
if request.format.json?
|
||||
result = if request.format.json?
|
||||
params.require(:product).slice(*permitted_attributes).permit!
|
||||
else
|
||||
params.require(:product).permit permitted_attributes
|
||||
end
|
||||
decode_base64_params result, :image
|
||||
end
|
||||
|
||||
BASE64_IMAGE_MATCHER = /^data:image\/(\w+);base64,/ # data:image/png;base64,
|
||||
# inspired by: https://stackoverflow.com/questions/32984963/upload-base64-encoded-image-with-paperclip-rails
|
||||
def decode_base64_params(authorized_params, attributes = [])
|
||||
tempfiles = []
|
||||
attributes = Array.wrap(attributes) # allow single attribute argument without array notation
|
||||
attributes.each do |attribute|
|
||||
if value = authorized_params[attribute].presence
|
||||
if value.is_a?(String) and match = value.match(BASE64_IMAGE_MATCHER)
|
||||
image_type = match[1]
|
||||
decoded_attribute = Base64.decode64 value.sub BASE64_IMAGE_MATCHER, ''
|
||||
file = Tempfile.new(['image', ".#{image_type}"])
|
||||
file.binmode
|
||||
file.write decoded_attribute
|
||||
authorized_params[attribute] = file
|
||||
end
|
||||
end
|
||||
end
|
||||
authorized_params
|
||||
ensure
|
||||
tempfiles.each &:unlink
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user