Skip to content

Me registed Callback "image" Not executing #463

@usman-174

Description

@usman-174

This is my Condig
`// src/config/unlayer.ts
import { UnlayerOptions } from 'react-email-editor';

export const editorConfig: UnlayerOptions = {
id: 'editor',
displayMode: 'email',
locale: 'en-US',

// Remove projectId or set to null to force custom image uploads
projectId: null,

appearance: {
theme: 'modern_light',
panels: {
tools: {
dock: 'left',

  },
},

},

features: {
preview: true,
imageEditor: false,
userUploads:{
enabled: true,
search: true,
},

textEditor: {
  spellChecker: true,
  emojis: true,
},

},

tools: {
form: {
enabled: true,
},
image: {
enabled: true,
},
},

blocks: [], // Custom blocks can be added here

designTags: {
saved_template: 'Saved Template',
newsletter: 'Newsletter',
promotional: 'Promotional',
transactional: 'Transactional',
},
};`

and this chunk of code

` const emailEditorRef = useRef(null);
// Updated useEffect for registering the image callback
const handleImageUpload = useCallback((file: any, done: Function) => {
console.log('Full file object:', file);

try {
  // The file structure might be different - let's handle multiple cases
  let uploadFile;

  if (file.attachments && file.attachments.length > 0) {
    uploadFile = file.attachments[0];
  } else if (file instanceof File) {
    uploadFile = file;
  } else if (file.file) {
    uploadFile = file.file;
  } else {
    console.error('Could not find file in:', file);
    throw new Error('No file provided or unrecognized file structure');
  }

  console.log('Upload file:', uploadFile);

  // Validate file type
  if (!uploadFile.type || !uploadFile.type.startsWith('image/')) {
    throw new Error('Please select a valid image file');
  }

  // Optional: Check file size (e.g., 5MB limit)
  const maxSize = 5 * 1024 * 1024; // 5MB
  if (uploadFile.size > maxSize) {
    throw new Error('Image size must be less than 5MB');
  }

  // Create FormData for upload
  const formData = new FormData();
  formData.append('file', uploadFile);
  formData.append('type', 'image');

  // Optional: Add additional metadata
  formData.append('source', 'email-editor');

  // Show initial progress
  done({ progress: 10 });

  // Upload to your API endpoint
  fetch('/api/upload-image', {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      // Add authorization headers if needed
      // 'Authorization': `Bearer ${localStorage.getItem('authToken')}`,
    },
    body: formData,
  })
    .then((response) => {
      console.log('Upload response status:', response.status);

      if (!response.ok) {
        throw new Error(
          `Upload failed: ${response.status} ${response.statusText}`,
        );
      }

      return response.json();
    })
    .then((data) => {
      console.log('Upload response data:', data);

      // Handle different response formats from your API
      const imageUrl =
        data.url || data.filelink || data.imageUrl || data.file_url;

      if (!imageUrl) {
        console.error('No URL in response:', data);
        throw new Error('No image URL returned from server');
      }

      // Complete the upload with the returned URL
      done({
        progress: 100,
        url: imageUrl,
      });

      toast.success('Image uploaded successfully!');
      console.log('Image uploaded successfully:', imageUrl);
    })
    .catch((error) => {
      console.error('Image upload failed:', error);
      toast.error(`Failed to upload image: ${error.message}`);

      // Mark upload as failed
      done({
        progress: 0,
        error: error.message,
      });
    });
} catch (error) {
  console.error('Upload setup failed:', error);
  toast.error(`Upload failed: ${(error as Error).message}`);
  done({
    progress: 0,
    error: (error as Error).message,
  });
}

}, []); // Remove dependencies to prevent recreation
useEffect(() => {
if (editorLoaded && emailEditorRef.current?.editor) {
// Register custom image upload callback
emailEditorRef.current.editor.registerCallback(
'image',
(file: any, done: Function) => {
console.log('Image upload callback triggered:', file);
handleImageUpload(file, done);
},
);

  console.log('Image upload callback registered');
}

}, [editorLoaded, handleImageUpload]);

`

when I upload an Image it is uploaded to unlayer server, I have done a lot of different things, but I cant seem to upload images to my own server

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions