It works.
I had just need to replace the
obj.write(Pathname.new(key))
with
obj.write(photo)
Question
Im developing a website with AngularJS in frontend that sends requests to a Rails 4 API backend. I have to manage quite images, so I would like to use Amazon S3 (but Im newbie with this and Im a bit lost).
Before using S3, I used an angular directive to upload images to Rails. Rails got this image and stored it in a path in the server.
Something like this:
... some code ...
# create the file path
path = File.join(directory, photoId.to_s)
# write the file
File.open(path, "wb") { |f| f.write(photo.read) }
where photo is the image uploaded to rails:
photo: #<ActionDispatch::Http::UploadedFile:0x00000002fd8250 @tempfile=#<Tempfile:/tmp/RackMultipart20140508-3746-1s70myo>, @original_filename="modernBoat.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"file\"; filename=\"modernBoat.jpg\"\r\nContent-Type: image/jpeg\r\n">
Im trying to do the same but instead of storing the photo in the Rails server, I would like to do it in S3. Im doing something like this (but I recognize, I dont completely understand how it works, so for sure something is wrong).
This is my code with S3:
def uploadPhotoToS3(entity, photo, id, photoId)
puts "uploadPhotoToS3.begin"
AWS.config(
:access_key_id => Yanpy::AWS_ACCESS_KEY_ID,
:secret_access_key => Yanpy::AWS_SECRET_ACCESS_KEY
)
bucketName = Yanpy::AWS_S3_BUCKET_NAME
fileName = '*** Provide file name ****'
s3 = AWS::S3.new
puts "S3=" + s3.inspect
bucket = s3.buckets[bucketName]
puts "bucket=" + bucket.inspect
key = "img/boats/1/2.jpg"
obj = bucket.objects[key]
puts "obj=" + obj.inspect
obj.write(Pathname.new(key))
puts "uploadPhotoToS3.end"
end
end
Im getting this error:
uploadPhotoToS3.begin
S3=<AWS::S3>
bucket=#<AWS::S3::Bucket:yanpy.dev>
obj=<AWS::S3::S3Object:yanpy.dev/img/boats/1/2.jpg>
Completed 500 Internal Server Error in 195ms
Errno::ENOENT (No such file or directory - img/boats/1/2.jpg):
app/controllers/uploads_controller.rb:184:in `uploadPhotoToS3'
app/controllers/uploads_controller.rb:73:in `create'
Im confused with the concepts of key and file name. Is the key the path where I would like to store my image in S3?
Solution
It works.
I had just need to replace the
obj.write(Pathname.new(key))
with
obj.write(photo)