Как использовать кроппер js в рельсах.6.0.2 - PullRequest
0 голосов
/ 03 мая 2020

Я реализовал кроппер js с помощью драгоценного камня, я имею в виду https://github.com/shrinerb/shrine/wiki/Image-Cropping, и это коды https://github.com/shrinerb/shrine-crop-example/, но это не работает, не появляются ошибки, почему не работает кроппер js?

приложение. html .erb

<!DOCTYPE html>
  <html>
   <head>
     <title>Prottype2</title>
     <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= stylesheet_pack_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
<%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
<link href="https://transloadit.edgly.net/releases/uppy/v1.6.0/uppy.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.css" rel="stylesheet" />

<script src="https://transloadit.edgly.net/releases/uppy/v1.6.0/uppy.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.6/cropper.js"></script>

 </head>

<body>
  <p class="notice"><%= notice %></p>
 <p class="alert"><%= alert %></p>
   <%= yield %>
 </body>

приложение. js

     //= require popper
    //= require bootstrap-sprockets

    require("@rails/ujs").start()
    require("turbolinks").start()
    require("@rails/activestorage").start()
    require("channels")
    require("jquery")


    function fileUpload(fileInput) {
     var formGroup = fileInput.parentNode
     var hiddenInput = document.querySelector('.upload-data')
      var imagePreview = document.querySelector('.image-preview img')

  formGroup.removeChild(fileInput)

    var uppy = Uppy.Core({
       autoProceed: true,
       restrictions: {
       allowedFileTypes: fileInput.accept.split(','),
      }
     })
     .use(Uppy.FileInput, {
      target: formGroup,
      locale: { strings: { chooseFiles: 'Choose file' } },
    })
      .use(Uppy.Informer, {
       target: formGroup,
    })
       .use(Uppy.ProgressBar, {
        target: imagePreview.parentNode,
    })
       .use(Uppy.ThumbnailGenerator, {
        thumbnailWidth: 600,
     })
       .use(Uppy.XHRUpload, {
       endpoint: '/upload',
    })

       uppy.on('upload-success', function (file, response) {
        imagePreview.src = response.uploadURL

       var uploadedFileData = JSON.stringify(response.body['data'])

       hiddenInput.value = uploadedFileData

       var copper = new Cropper(imagePreview, {
        aspectRatio: 1,
       viewMode: 1,
       guides: false,
       autoCropArea: 1.0,
       background: false,
       crop: function (event) {
       data = JSON.parse(hiddenInput.value)
       data['metadata']['crop'] = event.detail
        hiddenInput.value = JSON.stringify(data)
      }
    })
  })
 }

  document.querySelectorAll('input[type="file"]').forEach(function (fileInput) {
  fileUpload(fileInput)
})

cropbox. js

  import 'cropperjs/dist/cropper.css'

  import Cropper from 'cropperjs'

 function cropbox(image, url, { onCrop }) {
  image.src = url

   new Cropper(image, {
    aspectRatio: 1,
    viewMode: 1,
    guides: false,
    autoCropArea: 1.0,
    background: false,
    zoomable: false,
    crop: event => onCrop(event.detail)
  })
}

 export default cropbox

fileUpload. js

 import cropbox from 'cropbox'
 // ...
 uppy.on('upload-success', (file, response) => {
 // retrieve uploaded file data
 const uploadedFileData = response.body['data']

// set hidden field value to the uploaded file data so that it's submitted
// with the form as the attachment
hiddenInput.value = JSON.stringify(uploadedFileData)

cropbox(imagePreview, response.uploadURL, {
  onCrop(detail) {
    let fileData = JSON.parse(hiddenInput.value)
    fileData['metadata']['crop'] = detail
    hiddenInput.value = JSON.stringify(fileData)
  }
})
})

form. html .erb

  <%= form_with model: @blog_form , url: user_blogs_path ,local: true do |f| 
   %>

   <div class="field">
   <%  f.label :title %>
   <%= f.text_field :title %>
 </div>

<div class="field">
 <%  f.label :content %>
 <%= f.text_area :content %>
</div>

<div class="field">
 <%  f.label :user_id %>
 <%= f.hidden_field :user_id, value: current_user.id %>
</div>

<div class ="field">
   <%= f.fields_for  :photos, Photo.new do |photos_fileds|  %>

   <%= photos_fileds.label :image %>
   <%= photos_fileds.hidden_field :image, value: 
   photos_fileds.cached_image_data  if defined? 
   (photos_filed.cached_image_data) %>
   <%= photos_fileds.file_field  :image %><br/>
  <div>
     <img id="image" src="<%= photos_fileds.object.image_url %>" />
   </div>

   <% end %>

    </div>



   <%= f.submit "create", class: "btn btn-primary" %>
  <% end %>

application. s css

     /*
     * This is a manifest file that'll be compiled into application.css, 
     which will include all the files
     * listed below.
     *
     * Any CSS and SCSS file within this directory, lib/assets/stylesheets, 
      or any plugin's
     * vendor/assets/stylesheets directory can be referenced here using a 
      relative path.
     *
     * You're free to add application-wide styles to this file and they'll 
     appear at the bottom of the
     * compiled file so the styles you add here take precedence over styles 
     defined in any other CSS/SCSS
     * files in this directory. Styles in this file should be added after the 
     last require_* statement.
     * It is generally better to create a new file per style scope.
     *
     *= require_tree .
     *= require_self
     */
      @import "bootstrap";

     img {
       display: block;

        /* This rule is very important, please don't ignore this */
        max-width: 100%;
       }

       .image-preview img {
          display: block;
          max-width: 100%;
         }

        .image-preview {
           margin-bottom: 10px;
           display: inline-block;
           height: 300px;
        }

        img[src=""] {
           visibility: hidden;
          }

Вот когда вызывается response.uploadURL

application. js

   uppy.on('upload-success', function (file, response) {
      imagePreview.src = response.uploadURL

      var uploadedFileData = JSON.stringify(response.body['data'])

      hiddenInput.value = uploadedFileData

      var copper = new Cropper(imagePreview, {
      aspectRatio: 1,
      viewMode: 1,
      guides: false,
      autoCropArea: 1.0,
      background: false,
      crop: function (event) {
      data = JSON.parse(hiddenInput.value)
      data['metadata']['crop'] = event.detail
      hiddenInput.value = JSON.stringify(data)
     }
   })
  })
 }

fileUpload. js

  cropbox(imagePreview, response.uploadURL, {
   onCrop(detail) {
   let fileData = JSON.parse(hiddenInput.value)
   fileData['metadata']['crop'] = detail
   hiddenInput.value = JSON.stringify(fileData)
   }
  })

Я думаю, что uppy не находит селектор, так что не работает обрезка, поэтому я добавил селектор класса и идентификатора, но обрезка не работает

form_views

  <div class ="field form-group">
    <%= f.fields_for  :photos, Photo.new do |photos_fileds|  %>

    <%= photos_fileds.label :image , class: "form-control" %>
                                   **Add upload_data class**
    <%= photos_fileds.hidden_field :image,  class: "upload-data", value: 
    photos_fileds.object.cached_image_data %>
                                  **Add "select-files id**
   <%= photos_fileds.file_field  :image , class: "form-control ", id: 
   "select-files"%><br/>
   <div class="image-preview">
     <img id="image" src="<%= photos_fileds.object.image_url(:medium) %>" 
      height="300" class="rounded"  >
    </div>

 <% end %>
...