使用angular js通过rails paperclip提交文件

我正在尝试使用angular将文件作为参数发送到rails,然后让rails通过paperclip将该文件保存为用户附件。 我得到的最远的是获取上传内容的轨道,但它最终成为带有单行“目标文件”的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。 我试图避免添加新的依赖项,但如果没有其他好的方法,那就这样吧。 我非常感谢任何帮助/建议。

这个答案对我有很大的帮助,但我会仔细研究它的每一部分,以获得完整的答案。

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

在你的角度视图中:

  

在角度控制器中:

  $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