使用recorder.js时如何为CarrierWave设置content_type和original_filename

时间:2015-12-31 17:21:30

标签: ruby-on-rails ajax carrierwave recorder.js

我正在实施使用recorder.jsCarrierWave录制用户语音。 我可以通过这段代码保存声音,但仍然存在一些问题。

function saveSound() {
    recorder && recorder.exportWAV(function (blob) {
        var url = URL.createObjectURL(blob);

        var formData = new FormData();
        formData.append('voice[sound]', blob, "foo.wav");
        formData.append('voice[phrase_id]', $('#phrase').data('phrase-id'));
        $.ajax({
            type: "POST",
            url: "/voices",
            processData: false,
            contentType: false,
            data: formData
        });
    });
}

应用程序/模型/ voice.rb

class Voice < ActiveRecord::Base
  belongs_to :phrase
  belongs_to :user
  mount_uploader :sound, SoundUploader
end

这是由recorder.js创建的声音。

Voice.last.sound
=> #<SoundUploader:0x007fb5dda13818
 @file=#<CarrierWave::SanitizedFile:0x007fb5dda0bb18 @content_type=nil, @file="/Users/ironsand/dev/nativephrase/public/uploads/voice/sound/15/blob", @original_filename=nil>,
 @model=
  #<Voice:0x007fb5dc549e00
   id: 15,
   phrase_id: 24,
   user_id: nil,
   type: nil,
   gender: nil,
   created_at: Thu, 31 Dec 2015 17:11:48 UTC +00:00,
   updated_at: Thu, 31 Dec 2015 17:11:48 UTC +00:00,
   sound: "blob">,
 @mounted_as=:sound,
 @storage=#<CarrierWave::Storage::File:0x007fb5dda12d78 @uploader=#<SoundUploader:0x007fb5dda13818 ...>>,
 @versions={}>

因此,我在formData foo.wav中设置的名称将被忽略。如果我在ajax请求中设置content-type,我就无法上传声音。

如何设置CarrierWave模型的@content_type@original_filename

1 个答案:

答案 0 :(得分:1)

这适合我。

class MyUploader < CarrierWave::Uploader::Base

  include CarrierWave::RMagick
  include CarrierWave::MimeTypes

  process :set_content_type
  process :save_content_type

  def save_content_type
    model.content_type = file.content_type if file.content_type
  end

  def filename
    "#{model.type}_#{model.user_id}.xls" if original_filename
  end

end