Rails,部分从亚马逊s3下载文件

时间:2013-07-29 21:39:10

标签: ruby-on-rails amazon-s3

我有一个rails应用程序,我很乐意从Amazon S3下载部分文件,代码如下:

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

网址是正确的,我可以通过浏览器下载文件。但我在http.request命令中从amazon收到403错误:

res = http.request(req)
=> #<Net::HTTPForbidden 403 Forbidden readbody=true>

如何使用rails下载该文件? =)


顺便说一下,最后,我还有另一个解决方案。我需要该代码在将其上传到网站后检查曲目长度。所以它看起来像那样:     
上传轨道到S3 - &gt;下载部分内容 - &gt;检查长度
但后来我注意到,carrierwave首先自动将所有内容上传到tmp文件夹,因此上传过程实际上如下:    
上传到tmp - &gt;从网站上传到亚马逊s3 - &gt;除了 如果我们调用:before_save回调,我们将能够在上传到S3之前打开轨道。 所以代码看起来应该是这样的:

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

在那种情况下,我大量简化了这个过程:)

有一个性感的一天!

1 个答案:

答案 0 :(得分:2)

现在你只是向路径发出请求,我认为你还需要包含查询部分

full_path = (url.query.blank?) ? url.path : "#{url.path}?#{url.query}"
req = Net::HTTP::Get.new(full_path)

另见 - http://house9.blogspot.com/2010/01/ruby-http-get-with-nethttp.html

相关问题