使用angular-file-upload,carrierwave上传带参数的图像

时间:2015-12-06 20:13:18

标签: ruby-on-rails angularjs file-upload carrierwave multipartform-data

请帮助我: 我正在使用此指令angular-file-upload上传带参数的单个图像:

uploader = $scope.uploader = new FileUploader(
      url: '/recipes',
      alias:  'cover',
      removeAfterUpload:  true,
      #transformRequest: angular.identity,
      headers: {'X-CSRF-TOKEN': csrf_token,'accept': 'application/json'},
      withCredentials: true
    )


uploader.onBeforeUploadItem = (item)->
          #data = angular.toJSON($scope.recipe)
          item.formData.push("recipe": angular.toJson($scope.recipe))
          #item.upload()
          console.info('uploader', $scope.uploader);
          uploader.uploadAll()

这是创建动作:

def create

        @recipe = current_user.recipes.new(params.require(:recipe).permit(:name,:instructions))
        @recipe.user_id = current_user.id
        @recipe.save
        render 'show', status: 201
      end

这是请求:

Started POST "/recipes" for 127.0.0.1 at 2015-12-06 20:29:20 +0100
Processing by RecipesController#create as JSON
  Parameters: {"recipe"=>"{\"name\":\"cnfsl*k\",\"instructions\":\"mcdmùdsd\",\"ingredients\":[{\"id\":4,\"title\":\"sucre\"}]}", "cover"=>#<ActionDispatch::Http::UploadedFile:0xb42de9e8 @tempfile=#<Tempfile:/tmp/RackMultipart20151206-5852-txz5ls.jpg>, @original_filename="6.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"cover\"; filename=\"6.jpg\"\r\nContent-Type: image/jpeg\r\n">}

我收到了错误

undefined method `permit' for #<String:0xb40a6270>

任何人都可以帮助我

1 个答案:

答案 0 :(得分:0)

您的params[:recipe]不是hash,而是json。你需要先解析它。尝试将此行添加为create操作中的第一行:

params[:recipe] = JSON.parse params[:recipe]