内容
Rails Dropzoneのインストール、ドラッグアンドドロップとアップロードができるようにしたいが、、、
Rails環境で、ドラッグアンドドロップをやりたくて色々と試し、簡単と言われるがなかなかうまくできない。
ドラッグアンドドロップでアイコンが表示されるところまではOKなのに、削除ができない。
今ここ。
とりあえず、動画見ながら進んでいる。
そしてやっとアップロードまでできた。でも仕組みがよく理解できない。
ドラッグアンドドロップ、dropzone動画
以下の動画を見ながら進めている。
環境はMacOSX
1.Ruby on Rails Ajax Files Upload with Dropzone – Upload, Drag and drop files
2.Ruby on Rails Ajax Files Upload with Dropzone – List and delete file on server
途中まで進んだところで、ImageMagickが無いのでエラーになった。
未だ動かない
参考記事
http://www.workabroad.jp/tech/1118
引用「ImageMagickをイントールしていないのなら、エラーが出るはず。
CentOSにImageMagickをインストールするには下記。
Terminal
yum -y install libjpeg-devel libpng-devel
yum -y install ImageMagick ImageMagick-devel
」
Macの場合は
brew update # => update
brew install ImageMagick
ここまでもインストールできていないが、再起動するとエラーが無くなる
しかし、RemoveFileが正常に動作しない。
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
だめだあ、RMMagickがインストールできない。
少しずつやっているが、うまくいっていない。
これを参考にしてみる
validates_attachment :avatar,presence: true, content_type: { content_type: "image/jpeg" }, size: { in: 0..10.kilobytes } class User < ActiveRecord::Base has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/images/:style/missing.png" validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/ end
アップロードできた。なにが原因だったのか
もしドラッグアンドロップをRailsで実装したい人はソースを置きますので、参考にして下さい。
このドラッグアンドドロップのすごいのは、ドロップして削除をクリックするとサーバ側のファイルとDBのデータも削除してくれることです。そこら辺の仕組みがよくわからないのにちゃんと機能しているところがすごい。
うまくいったのは、再度動画を見ながら、きちんとタブ入れたり、インデントを整理したところ、正常に動作するようになりました。
自分のローカル環境、RUBYパスは
/Users/maseda/Documents/新書類/ruby_web/rails_dropzone
の環境で、ドラッグ・アンド・ドロップの表示ができました。
いろいろとディレクトリを作ったらどれが動くRAILSアプリのディレクトリかわからなくなります。
・原因
うまくいくと、今度は正常に動作しなかった状態に戻すことができないので推論になりますが、Rubyのuploads_controller.rbのファイルの記載でRubyコーディング規約に沿って記述していなかったのかもしれません。Pythonもそうですが、インデントやスペースを正しく入力しないとエラーになります。おそらくRailsでも同様のことが合ったのかも知れません。
ターミナルで
rails server
でWebrickを起動させて
http://localhost:3000/uploads
で表示させると、シンプルな画面が表示される。
そこに画像をドラッグ・アンド・ドロップする(いまは画像以外はアップロードされない)
rails Dropzone+paperclip ブログに記載
application.css
/* * *= require_tree . *= require dropzone/dropzone *= require_self */
application.js
//= require jquery //= require jquery_ujs //= require dropzone //= require turbolinks //= require_tree .
index.html.erb
<div id = "content"> <%= form_for @upload, html: {multipart: true, class: "dropzone" ,id: "my-dropzone"} do |f| %> <div class = "dz-message needsclick"> <h3>Drop file here</h3> </div> <div class = "fallback"> <%= f.file_field :image %> <%= f.submit "Upload the Image" %> </div> <% end %> </div>
routes.rb
Rails.application.routes.draw do resources :uploads, only: [:index, :create, :destroy] do collection do get :list #list_uploads_url end end # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end
upload.rb
class Upload < ApplicationRecord has_attached_file :image, :styles => { :medium => "300x300>",:thumb => "100x100>" } validates_attachment :image, :presence => true, :content_type => { :content_type => /\Aimage\/.*\Z/ }, :size => { :less_than => 2.megabyte } end
uploads_controller.rb
class UploadsController < ApplicationController def index @upload = Upload.new end def create @upload = Upload.new(upload_params) if @upload.save render json:{ message: "success", uploadId: @upload.id }, status: 200 else render json:{ error: @upload.errors.full_messages.join(", ") }, status: 400 end end def list uploads = [] Upload.all.each do |upload| new_upload = { id: upload.id, name: upload.image_file_name, size: upload.image_file_size, src: upload.image(:thumb) } uploads.push(new_upload) end render json:{ images: uploads} end def destroy @upload = Upload.find(params[:id]) if @upload.destroy render json:{ message: "file deleted from server"} else render json:{ message: @image.errors.full_messages.join(", ") } end end private def upload_params params.require(:upload).permit(:image) end end
upload.js.erb
$(function (){ Dropzone.autoDiscover = false; $("#my-dropzone").dropzone({ maxFilesize: 2, addRemoveLinks: true, dictRemoveFile:'削除', paramName: 'upload[image]', success: function(file, response){ $(file.previewElement).find('.dz-remove').attr('id',response.uploadId); $(file.previewElement).addClass('dz-success'); console.log("OK"); }, removedfile: function(file){ var id = $(file.previewTemplate).find('.dz-remove').attr('id'); $.ajax({ type: 'DELETE', url: "/uploads/" + id, success: function(data){ console.log(data.message); } }); var previewElement; return (previewElement = file.previewElement) != null ? (previewElement.parentNode.removeChild(file.previewElement)) : (void 0); }, init: function(){ var me = this; $.get("/uploads/list", function(data){ $.each(data.images,function(key, value){ if(data.images != undefined && data.images.length > 0 ){ me.emit("addedfile",value); me.emit("thumbnail",value,value.src); me.emit("complete",value); $(value._removeLink).attr("id",value.id); } }); }); } }); });