直接到Rails和React中的S3映像上传

时间:2017-06-25 18:38:51

标签: ruby-on-rails ruby reactjs amazon-s3 axios

我想直接从客户端上传图片,但我做得不好。有人能帮助我吗?

版本

  1. Rails 5.1.1
  2. ruby​​ 2.4.1
  3. aws-sdk 2.10.3
  4. 我的逻辑

    1. 药物并将图像拖放到Dropzone字段
    2. 通过axios进行ajax调用,然后获取signedUrl
    3. 通过使用signedUrl
    4. 发出put请求来上传图像文件

      客户端(反应):我正在使用react-dropzone

      handleOnDrop = (files) => {
          files.map(file => this.uploadImage(file))
      }
      
      uploadImage = (file) =>{
          axios.get('http://localhost:3000/upload/',
          {
            params: {
              filename: file.name
            }
          })
            .then(res => { 
              const signedUrl = res.data.url;
              return axios.put(signedUrl, file) 
            })
            .then((result) => console.log(result))
            .catch(e => console.log(e));
      }
      
      ...
      <Dropzone onDrop={this.handleOnDrop} >
      

      服务器端(Rails)

      配置

      Aws.config.update({
        region: 'us-east-2',
        credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']),
      })
      
      S3_BUCKET = Aws::S3::Resource.new.bucket(ENV['S3_BUCKET'])
      controller
      class S3Controller < ApplicationController
        def upload
           render json: S3_BUCKET.object("uploads/#{SecureRandom.uuid}/#{params[:filename]}").presigned_url(:get)
        end
      end
      

      的routes.rb

      ...
      get 'upload', to: 's3#upload'
      ...
      

      控制器

      class S3Controller < ApplicationController
        def upload
           render json: S3_BUCKET.object("uploads/#{SecureRandom.uuid}/#{params[:filename]}").presigned_url(:get)
        end
      end
      

      错误记录

      TypeError: Cannot read property 'protocol' of undefined
          at isURLSameOrigin (eval at <anonymous> (webpack-bundle.self-2cf7062….js?body=1:3328), <anonymous>:57:21)
          at dispatchXhrRequest (eval at <anonymous> (webpack-bundle.self-2cf7062….js?body=1:2070), <anonymous>:109:50)
          at Promise (<anonymous>)
          at xhrAdapter (eval at <anonymous> (webpack-bundle.self-2cf7062….js?body=1:2070), <anonymous>:12:10)
          at dispatchRequest (eval at <anonymous> (webpack-bundle.self-2cf7062….js?body=1:3265), <anonymous>:52:10)
          at <anonymous>
      

0 个答案:

没有答案