使用angular js通过rails paperclip提交文件 [英] Use angular js to submit file via rails paperclip

查看:134
本文介绍了使用angular js通过rails paperclip提交文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to use angular to send a file as a param to rails, and then have rails save that file as a user attachment via paperclip. The furthest I've gotten is getting rails to upload something, but it ends up being a txt file with the single line 'object file'.

这是相关的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。我试图避免添加新的依赖项,但如果没有其他好的方法,那就这样吧。我非常感谢任何帮助/建议。

As a last note, the file types that I'm trying to work with are doc/docx. I'm trying to avoid adding new dependencies, but if there's no other good way, then so be it. I really appreciate any help/suggestions.

推荐答案

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

This answer helped me a lot, but I going to go through every part of it to have a complete answer.

说你有一个用户带有头像属性的模型。

Say you have a User model with a avatar attribute.

在你的角度查看:

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

在角度控制器中:

    $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中:

In the 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

这篇关于使用angular js通过rails paperclip提交文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆