AngularJS/Rails Paperclip 文件上传

6
我正在尝试使用AngularJS/Rails和Paperclip gem实现文件上传。我用一个指令解决了文件输入问题。现在我想将图像与帖子的其他数据一起发送,但图像数据没有被发送。
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
}

因此,关于图像的任何数据都不会被发送到服务器,有什么提示如何实现这一点吗?

嘿,乔,这可能会有帮助 https://gist.github.com/vajapravin/48059fd9d64bb42f012f513cebd391ea - vajapravin
1个回答

0

我现在有进展了,我成功地通过form-data content-type发送了文件数据,但问题现在出现在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--

嗨@jeo-bow,您能否在Rails中使用Paperclip和AngularJS上传图像? - Vieenay Siingh

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接