13
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Paperclipでアップロードするファイルのcontent_typeの確認方法

Last updated at Posted at 2014-11-21

ご存知の通り、Paperclipは画像だけでなく各種ファイルをアップロードする機能をRailsアプリケーションに組み込むことのできる超便利gemです。

validates_attachment_content_typeのcontent_typeに渡すファイルタイプは、OSXであればfileコマンドで確認できます。

  • Excelの場合、
file -I sample-excel.xls
sample-excel.xls: application/vnd.ms-excel; charset=binary
  • Powerpointの場合、
file -I sample-powerpoint.pptx
sample-powerpoint.pptx: application/zip; charset=binary

あとはcontent_typeに以下のように設定すればOKですね。

validates_attachment_content_type col,
			:content_type => ["application/vnd.ms-excel", "application/zip"]

追記(2014.11.21)

上記の方法ではアップロード時にエラーになってしまうファイルタイプがありました(特にOffice製品)。
色々試行錯誤して調べた結果、下記のような設定にしたところアップロードすることが可能に。

拡張子 content_type
.doc application/msword
.docx application/vnd.openxmlformats-officedocument.wordprocessingml.document
.xls application/octet-stream
.xlsx application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.ppt application/vnd.ms-powerpoint
.pptx application/vnd.openxmlformats-officedocument.presentationml.presentation
.pdf application/pdf

調べ方は単純で地道にデバッグして変数の値を追います。
paperclipのコードをbundle openで開いて、attachement_content_type_validator.rbにブレークポイントを置きます。
以下のコードの場所にブレークポイントを置けば、アップロードに失敗したときに止まりますね。

def validate_each(record, attribute, value)
 
~(省略)~       
       
  if record.errors.include? attribute

    binding.pry #ブレークポイント
          
    record.errors[attribute].each do |error|
      record.errors.add base_attribute, error
    end
  end
end

引数でmodelオブジェクトが渡されてくる(record)ので、

record.{アップロードするフィールド}_contant_type 

で、modelに格納されているアップロードしたファイルのcontent_typeが確認できます。
やり方として正しいのかわかりませんが、とりあえず。

参考

How to validate file content type to pdf, word, excel, and plain terxt for paperclip?

13
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?