Inline Attachment x Active Store로 Github 같은 이미지를 설치하여 업로드하는 방법

13146 단어 RailsActiveStorage
Rails의 Active Storage로 Giithub과 Qita 등 이미지를 설치해 업로드해 봤습니다!

샘플 창고


ActiveStorage 설정

rails active_storage:install
rails db:migrate

InlineAttachment 설정

  • 필요한 파일을 InlineAttachment에서 app/assets/javascripts/이하로 다운로드
  • https://github.com/Rovak/InlineAttachment/blob/master/dist/inline-attachment.js
  • https://github.com/Rovak/InlineAttachment/blob/master/dist/jquery.inline-attachment.js
  • wget https://raw.githubusercontent.com/Rovak/InlineAttachment/master/dist/inline-attachment.js -P app/assets/javascripts/
    
    wget https://raw.githubusercontent.com/Rovak/InlineAttachment/master/dist/jquery.inline-attachment.js -P app/assets/javascripts/
    
  • 이번엔 수여inline-attachmenttextarea 응용 프로그램에서 그림을 드래그해서 업로드합니다.
  • post 요청 목표는/upload/image입니다.나중에 controller
  • 만들기
    app/assets/javascripts/application.js
    //= require inline-attachment
    //= require jquery.inline-attachment
    
    $(function(){
      $('.inline-attachment').inlineattachment({
        urlText: '<img src="{filename}">',
        uploadUrl: "/upload/image",
        uploadFieldName: "asset[file]",
        allowedTypes: ['image/jpeg', 'image/png', 'image/jpg', 'image/gif'],
        extraHeaders: {"X-CSRF-Token": $("meta[name=csrf-token]").attr("content")}
      });
    });
    

    jquery-rails 설정


    Inline Attachment에서 jquery를 사용하기 때문에 jquery-rails를 설정했습니다
    Gemfile
    gem 'jquery-rails'
    
    app/assets/javascripts/application.js
    //= require jquery
    

    이미지 업로드 controller로 만들기

  • 이번에는 이미지와 모델을 연결하는 것이 아니라 Active Storage의 직접 업로드를 사용합니다.
  • rails g controller upload image
    
    app/controllers/upload_controller.rb
    class UploadController < ApplicationController
      def image
        file = params[:asset][:file]
        blob = ActiveStorage::Blob.create_after_upload!(
          io: file,
          filename: file.original_filename,
          content_type: file.content_type
        )
    
        render json: { filename: url_for(blob) }
      end
    end
    

    이미지 업로드 확인용 scaffold

    rails g scaffold body:text
    
    rails db:migrate
    

    text_area class 건네주기

  • js에 정의된) 클래스 부여
  • 동시에 사이즈로 폭을 확대
  • app/views/posts/_form.html.erb
    <%= form.text_area :body, class: "inline-attachment", size: "100x50" %>
    

    eb를 수정하여 이미지 보기


    app/views/posts/show.html.erb
    <%== @post.body %>
    

    이미지 제작 테스트


    드래그 앤 드롭에 태그가 삽입되어 있습니다.
    로그에도 insert가 실행 중입니다.
    Started POST "/upload/image" for 127.0.0.1 at 2018-11-22 02:09:09 +0900
    Processing by UploadController#image as */*
      Parameters: {"asset"=>{"file"=>#<ActionDispatch::Http::UploadedFile:0x00007f0818760418 @tempfile=#<Tempfile:/tmp/RackMultipart20181122-19296-dyym8x.jpg>, @original_filename="image-1542820149354.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"asset[file]\"; filename=\"image-1542820149354.jpg\"\r\nContent-Type: image/jpeg\r\n">}}
      Disk Storage (1.6ms) Uploaded file to key: kw5WzruEFiiEDDwkqtNXZHnK (checksum: rkmRclvUbaP9VARI0QxhAw==)
       (0.1ms)  begin transaction
       app/controllers/upload_controller.rb:4
      ActiveStorage::Blob Create (0.3ms)  INSERT INTO "active_storage_blobs" ("key", "filename", "content_type", "metadata", "byte_size", "checksum", "created_at") VALUES (?, ?, ?, ?, ?, ?, ?)  [["key", "kw5WzruEFiiEDDwkqtNXZHnK"], ["filename", "image-1542820149354.jpg"], ["content_type", "image/jpeg"], ["metadata", "{\"identified\":true}"], ["byte_size", 33760], ["checksum", "rkmRclvUbaP9VARI0QxhAw=="], ["created_at", "2018-11-21 17:09:09.416249"]]
       app/controllers/upload_controller.rb:4
       (6.3ms)  commit transaction
       app/controllers/upload_controller.rb:4
    Completed 200 OK in 51ms (Views: 0.2ms | ActiveRecord: 7.4ms)
    

    기사를 써봤어요.

    성공했어!

    참고 자료

  • https://qiita.com/megane42/items/afc64a15adccf571445f
  • https://medium.com/weareevermore/manual-uploads-using-activestorage-47808dab1b65
  • 좋은 웹페이지 즐겨찾기