rails 3, heroku, aws-s3, simply trying to upload a

2019-08-31 10:36发布

问题:

Our app is hosted at Heroku, so no local file storage.

A third party api we're using doesn't store a WAV it creates, it POSTs the file (http/multi-part) back to our app. They provide sample code to 'simply' send that file on to S3. The code they supply (below) doesn't run on Rails 3 + Heroku. I suspect there's some different syntax for specifying the input file and temp file from which we read. (The code was originally for Sinatra. I have NO idea what the old [:filename] and [:tempfile] were for so I removed them and took a guess the syntax was something like this using Tempfile?)

  def post_audio_to_s3
    puts "*** POST_AUDIO_TO_S3 PARAMS:" + params.inspect

    con = AWS::S3::Base.establish_connection!(
      :access_key_id     => 'MYKEY',
      :secret_access_key => 'MYSECRET')

    puts "** CON='#{con.inspect}'"

    snd = AWS::S3::S3Object.store(params[:filename], 
                        Tempfile.open(params[:filename]).path, 
                        'bb_audios')
    puts "** SND='#{snd.inspect}'"

UPDATE: Almost works ,but zero length file created. I'm sort of flailing around with no idea how to use the Tempfile, but I added require 'tempfile' to the controller class and modified the S3 storage line to the above.

This whole POST-a-file to Heroku/Tempfile thing has my brain iced... any ideas would be appreciated. For one thing... I have no idea where the DATA comes from... shouldnt I see something besides the filename when I inspect the params if it's being POSTED to the app?

回答1:

It should work the same way as HTML form file upload

<form action="/post_audio_to_s3" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file"/>
<input type="submit" value="Upload"/>
</form>

Try testing your action using that the form first. And then make sure your third party api is giving you the file as a multipart-data HTML POST submit.



回答2:

The answer was as follows. We had to change the url parameter from filename= to myfilename= because the rails magic automatically uses 'filename' for the POSTed data so they were stomping over each other in the params[].

openme = params['filename'].tempfile.path

snd = AWS::S3::S3Object.store(params[:myfilename], 
                        File.open(openme), 
                        'MYBUCKET')