Reputation: 2264
I'm trying to allow POSTs to a JSON API in rails that contain multiple images. I've been having trouble finding info that relates to an API upload with has_many instead of nested_attributes.
I have this from the params in the controller.
{"component_1"=>
#<ActionDispatch::Http::UploadedFile:0x007f8b4b5ac188
@content_type="image/png",
@headers=
"Content-Disposition: form-data; name=\"images[component_1]\"; filename=\"test.png\"\r\nContent-Type: image/png\r\nContent-Length: 2125\r\n",
@original_filename="test.png",
@tempfile=
#<File:/var/folders/t_/991c5xb934q_d6z13gg__7br0000gn/T/RackMultipart20130531-45537-dywznr>>,
"component_2"=>
#<ActionDispatch::Http::UploadedFile:0x007f8b4b5ac0e8
@content_type="image/png",
@headers=
"Content-Disposition: form-data; name=\"images[component_2]\"; filename=\"icon.png\"\r\nContent-Type: image/png\r\nContent-Length: 4235\r\n",
@original_filename="icon.png",
@tempfile=
#<File:/var/folders/t_/991c5xb934q_d6z13gg__7br0000gn/T/RackMultipart20130531-45537-ju4uy>>
}
I have a model with an uploader defined.
How do I actually save the images from the UploadedFiles? Also, I want to rename them, and I don't want any temporary files hanging around after I've stored the image.
Upvotes: 2
Views: 931
Reputation: 3909
It's hard to comment without seeing your controller or model code, but with that being said, the answer should be pretty straight forward.
Let's say you have an Image model with an uploader mounted on the image_file column. If you are creating a new Image object in your controller, then you do something like Image.create(image_file: params[:component_<number>])
for each image component uploaded. That should give you an idea of how it works, but their may be more gracefully methods to do this (nested_attributes for one)
Upvotes: 1