如何使用rails,angular& amp;将图像上传到S3回形针

时间:2016-03-11 16:26:02

标签: ruby-on-rails angularjs amazon-s3 paperclip

我是Angular-Rails的新手,我想创建一个具有上传到AWS S3的图像附件的表单。我使用传统方法(普通表格和回形针宝石)成功上传了图像。

所以希望有人可以解决我的问题。

这是我的rails控制器:

class ProjectsController < ApplicationController
  before_action :set_project, only: [:show, :edit, :update, :destroy]

  # GET /projects
  # GET /projects.json
  def index
    render json: Project.all
  end

  # POST /projects
  # POST /projects.json
  def create

    @project = Project.new(project_params)
    if @project.save
      render json: @project
    else
      render json: @project.errors
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_project
      @project = Project.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def project_params
      params.require(:project).permit(:name, :description, :image)
    end
end

这是我的角度控制器:

app.controller('HomeCtrl', ['$scope','Upload',function($scope, Upload){

  // upload later on form submit or something similar
  $scope.submit = function() {
    if ($scope.form.file.$valid && $scope.file) {
      $scope.upload($scope.file);
    }
  };

  // upload on file select or drop
  $scope.upload = function (file) {
    Upload.upload({
        url: '/projects',
        data: {file: file, 'project[name]': $scope.name, 'project[description]': $scope.description},
    }).then(function (resp) {
        console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);

    }, function (resp) {
        console.log('Error status: ' + resp.status);
    }, function (evt) {
        var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
        console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
    });
  };

}]);

这是我的角度观点:

<form name="form">
  <input type="text" ng-model="name"><br />
  <input type="text" ng-model="description"><br />

  <div class="button" ngf-select ng-model="image" name="image" ngf-pattern="'image/*'"
      ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100" 
      ngf-resize="{width: 100, height: 100}">Select</div><br />

  <button type="submit" ng-click="submit()">submit</button>

 </form>

这就是我得到的回报: image of what project returns

1 个答案:

答案 0 :(得分:0)

将此指令用于文件上传https://github.com/mistralworks/ng-file-model/

它会将文件转换为base64。您可以通过回形针直接上传,如下所示

if (token.IsCancellationRequested) return;

在控制器中添加require def create @project = Project.new(project_params) file = Paperclip.io_adapters.for(put base64 data of file) file.original_filename = "avatar_name" @project.image= file if @project.save render json: @project else render json: @project.errors end end

base64