将文件传递到后端的回形针

将文件传递到后端的回形针

本文介绍了将文件传递到后端的回形针 [rails]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用回形针将多个文件附加到一个条目对象

I am using paperclip to attach multiple files to a Entry object

Class Asset < ActiveRecord::Base

    belongs_to :entry

    has_attached_file :asset, ...

当用户通过嵌套表单上传文件时效果很好.但是,在某些情况下,文件不是通过输入表单上传的,而是通过闪存录音机上传的.音频被异步录制并上传到我的/tmp 文件夹.所以我最终在我的服务器上得到了一些没有通过回形针上传的文件.

Works wonderfully when user is uploading files via a nested form. However, I have certain instances in which a file is uploaded not via the input form but as a result of a flash audio recorder. Audio is recorded and uploaded asynchronously to my /tmp folder. So I end up with some files on my server that have not been uploaded via paperclip.

在这些情况下,我想获取文件并将其传递给回形针进行处理,就像用户通过输入表单上传一样.即我需要在控制器内以编程方式使用回形针.

In these cases, I'd like to take the file and pass it to paperclip to be handled as if it were uploaded by a user via the input form. i.e. I need to utilize paperclip programmatically from within a controller.

您将如何实现这一目标?非常感谢!

How would you go about accomplishing this? Many thanks!

推荐答案

通常,上传的文件会作为 params 散列中的 File 对象传递给您的控制器,其中然后由构造函数通过 attributes= 传递给由 Paperclip 的 has_attached_file 创建的 setter 方法 - 在您的模型的情况下 Asset#asset=(可能想稍微澄清一下这些名称).

Ordinarily an uploaded file is passed to your controller as a File object in the params hash, which is then handed by the constructor, by way of attributes=, to the setter method created by Paperclip's has_attached_file--in your model's case Asset#asset= (might want to clarify those names a bit).

不,这不是您问题的答案,但它引导我们找到答案.知道您可能意识到您可以随时使用 File 作为参数调用该 setter.例如:

No, that's not an answer to your question, but it leads us to the answer. Knowing that you might realize that you can call that setter any time you want with a File as the parameter. E.g.:

class SomeController < ActionController::Base
  def some_action
    @some_asset = Asset.find 123 # (for example)

    file_path = '/tmp/path/to/your/file'
    file      = File.open(file_path, 'r')

    @some_asset.asset = file
    @some_asset.save
  end
end

希望对你有帮助!

这篇关于将文件传递到后端的回形针 [rails]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 23:20