【问题标题】:Use angular js to submit file via rails paperclip使用angular js通过rails回形针提交文件
【发布时间】:2015-04-27 20:38:35
【问题描述】:

我正在尝试使用 angular 将文件作为参数发送到 rails,然后让 rails 通过回形针将该文件保存为用户附件。我得到的最远的东西是让 rails 上传一些东西,但它最终是一个带有单行“目标文件”的 txt 文件。

这是相关的 Angular

a.uploadAnonRes = function(app){
  if(window.FileReader){ console.log("supported")};
  console.log(($('.anonUploadField'))[0].files);
  http = {
    method: "PUT",
    url: '/admin/upload_anon_res.json',
    params: {
      anon_file: btoa(($('.anonUploadField'))[0].files[0]),
      user_id: app.raw_app.user_id
    }
  };
  $http(http).success(function(data){
      console.log("success");
  });
};

这是相关的轨道

def upload_anon_res
 user = User.find(params[:user_id])
 user.anon_resume = decode_res
 user.save
 respond_to do |format|
  format.json{ render json: user, root: false }
 end
end

def decode_res
 decoded_data = Base64.decode64(params[:anon_file])
 data = StringIO.new(decoded_data)
 return data
end

最后一点,我尝试使用的文件类型是 doc/docx。我试图避免添加新的依赖项,但如果没有其他好方法,那就这样吧。我非常感谢任何帮助/建议。

【问题讨论】:

    标签: javascript ruby-on-rails ruby angularjs ruby-on-rails-3


    【解决方案1】:

    answer 给了我很多帮助,但我会仔细阅读它的每个部分以获得完整的答案。

    假设您有一个带有avatar 属性的User 模型。

    在您的角度视图中:

    <input type="file" name="avatar" onchange="angular.element(this).scope().uploadFile(this.files)" />
    

    在 Angular 控制器中:

        $scope.uploadFile = function(files) {
            var fd = new FormData();
            fd.append('user[avatar]', files[0]); // 'user[avatar]' is important, so that params[:user][:avatar] contains the file, as expected by Rails
            $http.put('/users.json', fd, { // The update method of the users controller
                withCredentials: true,
                headers: {
                    'Content-Type': undefined,
                    'X-CSRF-Token': $('meta[name=csrf-token]').attr('content')
                },
                transformRequest: angular.identity
            }).success(function(e) {
                console.log(e);
            }).error(function(e) {
                console.log(e);
            });
        };
    

    在 UserController.rb 中:

    class UserController < ApplicationController
      def update
        @user = User.find(params[:id])
        @user.assign_attributes(user_allowed_parameters)
        if (@user.save)
          render json: {msg: 'Successfully updated'}
        else
          render json: {msg: @user.errors.full_messages}, status: 500
        end
      end
    
      private
    
      def user_allowed_parameters
        params.fetch(:user, {}).permit(
          :first_name, 
          :last_name,
          :email,
          :avatar
        )
      end
    end
    

    【讨论】:

    • 我刚刚花了好几个小时寻找fd.append('user[avatar]', files[0]);。你是圣人!
    猜你喜欢
    • 2018-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    • 2011-12-05
    • 1970-01-01
    相关资源
    最近更新 更多