6

我尝试使用 Paperclip gem 使用 AngularJS/Rails 实现文件上传。我用指令修复了文件输入问题。现在我想用帖子的其他数据发送图像,但图像数据没有发送。

HTML:

<form name="PostForm" ng-submit="submit()" novalidate>
  <input type="text" ng-model="post.title">
  <input type="file" file-upload />
  <textarea ng-model="post.content"></textarea>
</form>

我的控制器:

$scope.create = function() {

    function success(response) {
        console.log("Success", response)
        $location.path("posts");
    }

    function failure(response) {
        console.log("Failure", response);
    }

    if ($routeParams.id)
        Post.update($scope.post, success, failure);
    else
        Post.create($scope.post, success, failure);
    }

$scope.$on("fileSelected", function (event, args) {
    $scope.$apply(function () {
        $scope.post.image = args.file;
    });

我的模型:

class Post < ActiveRecord::Base
  attr_accessible :content, :title, :image_file_name, :image_content_type, :image_file_size, :image_updated_at

  belongs_to :user
  has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
end

但是当我将它发送到服务器端时,请求是这样的:

{
  "content":"Hey",
  "created_at":"2013-08-31T17:54:32Z",
  "id":17,
  "image_content_type":null,
  "image_file_name":null,
  "image_file_size":null,
  "image_updated_at":null,
  "title":"Image",
  "updated_at":"2013-08-31T17:54:32Z",
  "user_id":4
}

所以,没有关于图像的数据被发送到服务器,关于如何做到这一点的任何提示?

4

1 回答 1

0

我现在进步了,我成功通过 form-data 内容类型发送文件数据,问题现在在 rails 控制器中,启动错误:

undefined method `stingify_keys`

这是我用来发送数据的代码:

$http({
        method: 'POST',
        url: url,
        headers: { 'Content-Type': false },
        transformRequest: function (data) {
            var formData = new FormData();
            formData.append("post", angular.toJson(data.post));
            formData.append("image", data.image);
            return (formData);
        },
        data: { post: $scope.post, image: $scope.image}
    }).
success(function (data, status, headers, config) {
    alert("success!");
}).
error(function (data, status, headers, config) {
    alert("failed!");
});

这就是发送到 rails 的数据:

-----------------------------2122519893511
Content-Disposition: form-data; name="post" {"title":"sdsdsd","content":"sdsd"}
-----------------------------2122519893511
Content-Disposition: form-data; name="image"; filename="dad.jpg" Content-Type: image/jpeg [image-data]
-----------------------------2122519893511--
于 2013-09-01T07:54:57.183 回答