erossini / EasyMarkdownEditor

Easy Markdown Editor is a simple, beautiful, and embeddable JavaScript Markdown editor. Delightful editing for beginners and experts alike. Features built-in autosaving and spell checking.
https://puresourcecode.com/javascript/new-markdowneditor-components-for-javascript-and-blazor/
MIT License
1 stars 1 forks source link

uploadImage: How to insert link tag for files and image tag for images? #1

Open steinhaug opened 2 weeks ago

steinhaug commented 2 weeks ago

Hei,

I have just started using this editor and I am using your build it seems. I am using the following config:

    const easyMDE = new EasyMDE({  
        element: document.getElementById('my-text-area'),  
        uploadImage:true,  
        imageUploadEndpoint: 'uploader.php',  
        imagePathAbsolute: true,  
        imageMaxSize: 1024 *1024 * 100  
    });

The uploader handles the upload, straight forward using $_FILES. Then on success returns JSON:

{
    "status": "success",
    "data": {
        "filePath": "\/my-full-path\/for-uploads-directory\/my-uploaded-file.png"
    }
}

This will insert markup in the editor looking like:

![my-uploaded-file.png](/my-full-path/for-uploads-directory/my-uploaded-file.png)

Here is my question,

as the uploader will insert anything. Say I drag'n'drop a PDF file instead of an image, my uploader saves the PDF file and returns it as if it were an image. Now how could I make it drop the exclamation mark so it becomes a link instead ?

// This would be a perfect insert when uploading a PDF, ZIP file or some none image file.
[my-uploaded-file.pdf](/my-full-path/for-uploads-directory/my-uploaded-file.pdf)

// This works like a charm already, if the file is an image
![my-uploaded-file.png](/my-full-path/for-uploads-directory/my-uploaded-file.png)

What if I added some more data for the returned JSON. However I have no clue how I would access or benefit from this with the Markdown editor. I would like to add name and type, see examples below.

Is there an easy fix for this in the config for easyMDE ?

{
    "status": "success",
    "data": {
        "filePath": "\/my-full-path\/for-uploads-directory\/my-uploaded-file.png",
        "fileName": "uploaded-image",
        "fileType": "image", // image or link
    }
}

> ![uploaded-image](/my-full-path/for-uploads-directory/my-uploaded-file.png)

{
    "status": "success",
    "data": {
        "filePath": "\/my-full-path\/for-uploads-directory\/brochure.pdf",
        "fileName": "PDF file",
        "fileType": "link", // image or link
    }
}

> [PDF file](/my-full-path/for-uploads-directory/brochure.pdf)
steinhaug commented 2 weeks ago

For those that might be looking, a basic uploader script for the above setup in PHP could look like this:

uploader.php

// Define the upload directory
$upload_dir = dirname(dirname(__DIR__)) . '/files/markdown/';         // on server
$web_upload_dir = '/files/markdown/';                                 // in browser

// Function to sanitize filename
function sanitize_filename($filename) {
    // Remove any character that isn't a word character, dash, or dot
    $filename = preg_replace('/[^\w\-\.]/', '', $filename);
    // Remove any leading or trailing dots
    $filename = trim($filename, '.');
    return $filename;
}

// Function to generate a unique filename
function generate_unique_filename($upload_dir, $filename) {
    $info = pathinfo($filename);
    $base_name = $info['filename'];
    $extension = isset($info['extension']) ? '.' . $info['extension'] : '';
    $counter = 0;

    while (file_exists($upload_dir . $filename)) {
        $counter++;
        $filename = $base_name . '_' . $counter . $extension;
    }

    return $filename;
}

// Check if a file was uploaded
if (isset($_FILES['image']) && $_FILES['image']['error'] == 0) {
    $original_filename = $_FILES['image']['name'];
    $tmp_name = $_FILES['image']['tmp_name'];

    // Sanitize the filename
    $safe_filename = sanitize_filename($original_filename);

    // Generate a unique filename
    $unique_filename = generate_unique_filename($upload_dir, $safe_filename);

    // Get file information
    $file_info = pathinfo($unique_filename);
    $filename_without_extension = $file_info['filename'];
    $extension = isset($file_info['extension']) ? $file_info['extension'] : '';

    // Attempt to move the uploaded file
    if (move_uploaded_file($tmp_name, $upload_dir . $unique_filename)) {
        // Success
        $response = [
            'status' => 'success',
            'original_filename' => $original_filename, // uploaded filename
            'saved_filename' => $unique_filename,      // dirified filename
            'extension' => $extension,
            'filename_without_extension' => $filename_without_extension,
            'data' => [
                'filePath' => $web_upload_dir . $unique_filename
            ]
        ];

    } else {
        // Failure
        $response = [
            'status' => 'error',
            'message' => 'Failed to move uploaded file.'
        ];
    }

} else {
    // No file uploaded or upload error
    $response = [
        'status' => 'error',
        'message' => 'No file uploaded or upload error occurred.'
    ];
}

// Send JSON response
header('Content-Type: application/json');
echo json_encode($response);