简体   繁体   中英

Unable to preview image after converting attachment to Base64 using Trix

I'm using Trix, and for uploading attachments our backend developer tells me that I should convert the attachment to base64 and save the base64 data to the database instead of uploading the binary file.

I wrote this code for implementing it, and the output of the input field(HTML) is working as expected, but the image preview doesn't show in the editor.

$(function() {

  $(document).on('trix-attachment-add', function(event) {
    var attachment = event.originalEvent.attachment;
    // Convert data URLs to File objects.
    if(attachment.file) {
      return uploadAttachment(attachment);
    } else {
      console.error('Could not upload attachment.');
      console.error(attachment);
      attachment.remove();
    }
  });

});

function uploadAttachment(attachment) {
  var reader = new FileReader();
  console.log(attachment)

      // Set the reader to insert images when they are loaded.
      reader.onload = function (e) {
        var result = e.target.result;
        var attrs = {
          src : result,
          url: result,
          href : ''
        };
        attachment.setAttributes(attrs)
        attachment.setUploadProgress(100);
      }
      // Read image as base64.
      reader.readAsDataURL(attachment.file);
    }

I don't know what causes this problem.

Try replacing

$(document).on('trix-attachment-add', function(event) {

with

document.addEventListener("trix-attachment-add", function(event) {

This could be event listeners being cached thus firing multiple times. The first load of image works, it could be the next loads that make this look busted.

Could also be Turbolinks issue so wrap your code with this instead:

$(document).on('turbolinks:load', function() {

我设法通过设置fileObjectURL属性来解决这个问题,如下所示

attachment.attachment.fileObjectURL = result;

Complete code for latest version (works with Symfony 6 easy admin bundle):

(function() {
function asBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}
document.addEventListener("trix-file-accept",  function(event) {
    event.preventDefault();
    if (event.file) {
        asBase64(event.file).then(function(data) {
            let image = document.createElement('img');
            image.src = data;
            let tmp = document.createElement('div');
            tmp.appendChild(image);
            let editor = document.querySelector('trix-editor');
            editor.editor.insertHTML(tmp.innerHTML);
        }).catch(e => console.log(e));
    }
}); })();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM