Note that there are some explanatory texts on larger screens.

plurals
  1. PODownloading S3 files(objects) using aws-sdk for ruby in rails
    text
    copied!<p>I am not using paperclip or carrierwave or any other gems for interaction with amazon web services s3. In fact, I am not using any models, just directly interacting with S3 objects.</p> <p>Can someone please provide some code as to how to directly download objects(files) from AWS S3</p> <p>This is my code so far :</p> <p><strong>View:</strong></p> <pre><code>&lt;h2&gt;Download Files&lt;/h2&gt; &lt;%@root_files.each do |file| %&gt; &lt;% next if @obj %&gt; &lt;td&gt;Filename: &lt;b&gt;&lt;%= file %&gt;&lt;/b&gt;&lt;/td&gt; &lt;td&gt;&lt;%= link_to "Download", download_url_for(file) %&gt;&lt;/td&gt; &lt;% end %&gt; </code></pre> <p>Corresponding <strong>Controller:</strong></p> <pre><code>def xxx bucket = AWS::S3.new.buckets[ ENV["BUCKET"]] @root_files = bucket.as_tree.children.select(&amp;:leaf?).collect(&amp;:key) end </code></pre> <p><strong>download_url_for method</strong>:</p> <pre><code>def download_url_for(file_key) s3 = AWS::S3.new bucket = s3.buckets[ ENV["BUCKET"]] object = bucket.objects[file_key] File.open('xxxxx', 'wb') do |file| object.read do |chunk| file.write(chunk) end end end </code></pre> <p>I need to be able to save the downloaded file on any browsable non-pretedetermined location on my desktop.Id really appreciate view on how to modify the download_url_for method to achieve this.</p> <p>===================================== I just tried using </p> <pre><code>&lt;td&gt;&lt;%= link_to "Download",object.value.url_for(:read).to_s %&gt;&lt;/td&gt; </code></pre> <p>But on downloading I only get a zip file with xml content inside it, not the original file (word document in my case) --- any thoughts on how to modify this so as to get the actual file type and contents? Thanks</p> <p>=======================Heres my code for uploading the file</p> <p><strong>View code:</strong></p> <pre><code>&lt;%= form_tag({:action =&gt; 'create_file'}, multipart: true) do %&gt; &lt;%= file_field_tag 'uploaded_file' %&gt;&lt;br /&gt; &lt;%= submit_tag 'Upload' %&gt; &lt;br /&gt; &lt;% end %&gt; </code></pre> <p><strong>Controller action</strong> - create_file action</p> <pre><code>def create_file s3 = AWS::S3.new bucket = s3.buckets[ENV["BUCKET"]] key = params[:uploaded_file].original_filename object = bucket.objects[key] object.write(params[:uploaded_file].read) end </code></pre> <p>Can someone suggest as to how I can check the MIME type or preserve the filename while uploading if thats the issue as mentioned by @Frederick Cheung? thanks</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload