2016-02-26 61 views
2

我的回形针(带有S3)在我的应用程序中工作,用于音频文件。模型定义连接S3和回形针。没有视图的回形针

# attachments 
has_attached_file :audio, storage: :s3, s3_credentials: Proc.new{|a| a.instance.s3_credentials} 
validates_attachment_content_type :audio, :content_type => [ 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3', 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg', 'audio/x-mpegaudio' ] 

我可以通过轨道simple_form上传的文件,使用此代码:

<%= simple_form_for(@sentence) do |f| %> 
    <%= f.error_notification %> 
    . 
    <%= f.input :audio, as: :file %> 
    . 
<% end %> 

我也想创建使用背景(Resque)处理音频。此代码从Web API检索音频流并尝试将其保存到现有的模型实例。这是行不通的。

sentences.each do |sentence| 
    sentence.audio = get_audio(sentence.sentence) 
    sentence.save 
end 

回形针似乎不知道如何处理音频流。

failed: #<Paperclip::AdapterRegistry::NoHandlerError: No handler found for "\xFF\xF3\xC8\xC4\x00\x00\x00\x03H\x00\x00\x00\x00LAME3.99.5\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0 

** **进展

我取得了一些进展:写的音频流的将它视为......但现在回形针抱怨编码

def get_audio_tempfile(target) 
    audio = translator.speak "#{target}", :language => "#{@language_cd}", :format => 'audio/mp3', :options => 'MaxQuality' 
    tempfile = Tempfile.new("target_temp.mp3") 
    tempfile.binmode 
    tempfile.write(audio) 
    tempfile.close 
    tempfile.open 
    tempfile 
end 

错误:

[paperclip] Content Type Spoof: Filename target_temp.mp320160226-32064- r391y9 (audio/mpeg from Headers, [] from Extension), content type discovered from file command: audio/mpeg. See documentation to allow this combination. 

回答

1

我不明白你的get_audio方法在做什么,但你需要确保它返回一个文件句柄,例如

sentence.audio = File.new(path_to_your_file, "r") 
sentence.save 

至于你将它视为办法,确保这样的

Tempfile.new([ 'foobar', '.mp3' ]) 

创建这样的回形针不会抱怨文件扩展名

0

如何保存音频摘要流到Paperclip/S3而不通过视图。

假设回形针工作并写入S3,需要从视图以外的其他地方上传文件(使用Paperclip)(在我的情况下,它是Resque进程)。

为什么这样做:允许修复前台和后台处理,或批量上传大量数据。

模式

# attachments 
    has_attached_file :audio, storage: :s3, s3_credentials: Proc.new{|a| a.instance.s3_credentials} 
    validates_attachment_content_type :audio, :content_type => [ 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3', 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg', 'audio/x-mpegaudio' ] 

视图

<%= simple_form_for(@sentence) do |f| %> 
    <%= f.error_notification %> 
    . 
    <%= f.input :audio, as: :file %> 
    . 
<% end %> 

工作

sentence.audio = get_audio_tempfile(sentence.sentence) 
sentence.save 

的get_ audio_tempfile

def get_audio_tempfile(target) 
    audio = translator.speak "#{target}", :language => "#{@language_cd}", :format => 'audio/mp3', :options => 'MaxQuality' 
    tempfile = Tempfile.new(['target_temp','.mp3']) 
    tempfile.binmode 
    tempfile.write(audio) 
    tempfile.rewind 
    tempfile 
end 

重要提示:

  • 包括正确的文件扩展名
  • 退的临时文件
  • 使用它之前,不要关闭临时文件

谢谢@tobmatth帮助解决文件问题。