Reputation: 154
I have a rails application and I would love to download part of the file from Amazon S3 with following code:
url = URI.parse('https://topdisplay.s3-eu-west-1.amazonaws.com/uploads/song/url/15/09_-_No_Goodbyes.mp3?AWSAccessKeyId=dfsfsdf@fdfsd&Signature=fsdfdfdgfvvsersf') # turn the string into a URI
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true #S3 uses SSL, isn't it?
req = Net::HTTP::Get.new(url.path) # init a request with the url
req.range = (0..4096) # limit the load to only 4096 bytes
res = http.request(req) # load the mp3 file
Mp3Info.open( StringIO.open(res.body) ) do |m| #do the parsing
puts m
end
The url is correct, I can download a file through browser. But I get 403 error from amazon at http.request command:
res = http.request(req)
=> #<Net::HTTPForbidden 403 Forbidden readbody=true>
How I can download that file with rails? =)
By the way, finally, I've got another solution. I needed that code to check track length after uploading it to the website. So it was looked like that:
upload track to S3 -> download part of it -> check length
But later I've noticed that carrierwave automatically uploads everything to tmp folder first, so uploading process actually looks like that:
upload to tmp -> upload from website to amazon s3 -> save
And if we call :before_save callback we will be able to open track before it's uploading to S3.
So the code should look like that:
before_save :set_duration
Mp3Info.open( 'public'+url.to_s ) do |m| #do the parsing
self.duration = m.length.to_i
self.name = m.tag.title if self.name == ""
end
In that case I simplified the process a lot :)
Have a sexy day!
Upvotes: 0
Views: 459
Reputation: 20614
right now you are only making a request to the path, i think you need to include the query portion as well
full_path = (url.query.blank?) ? url.path : "#{url.path}?#{url.query}"
req = Net::HTTP::Get.new(full_path)
see also - http://house9.blogspot.com/2010/01/ruby-http-get-with-nethttp.html
Upvotes: 2