0

我用神社 gem 实现了cropper js,我参考https://github.com/shrinerb/shrine/wiki/Image-Cropping,这段代码https://github.com/shrinerb/shrine-crop-example/,但是不行,不出现错误,为什么cropper 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)
})

裁剪框.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

文件上传.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 %>

应用程序.scss

     /*
     * 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

应用程序.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)
     }
   })
  })
 }

文件上传.js

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

我认为 uppy 没有找到选择器,因此无法裁剪,因此我添加了类和 id 选择器,但裁剪仍然不起作用

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 %>
4

0 回答 0