Ionaru / easy-markdown-editor

EasyMDE: A simple, beautiful, and embeddable JavaScript Markdown editor. Delightful editing for beginners and experts alike. Features built-in autosaving and spell checking.
https://stackblitz.com/edit/easymde
MIT License
2.45k stars 319 forks source link

Is there any working example on how to use the imageUploadFunction #574

Open Underest opened 11 months ago

Underest commented 11 months ago

There was a similar question #334, but the answer to that is not working that well. The image is displayed kinda weird.

In Markdown, it looks like this: image When Im using the preview it looks like this: image But as soon as I click on the "Z", it looks like this: image And there is no other way to go out of the preview, than reloading the website.

The answer to question #334 was this code:

(file, onSuccess, onError) => {
  const reader = new FileReader();
  reader.onload = () => onSuccess(reader.result);
  reader.onerror = () => onError("Error loading"+file.name);
  reader.readAsDataURL(file)

In total my Editor looks like this:

const easyMDE = new EasyMDE({
            element: document.getElementById("example"),
            placeholder: "Nach dem schreiben bitte speichern",
            toolbar: [
                "bold","italic","heading","|","code","quote","|","unordered-list","ordered-list","table","|","link","upload-image","|","preview","side-by-side","fullscreen","|","guide"
            ],
            uploadImage: true,
            imageUploadFunction:
            (file, onSuccess, onError) => {
                const reader = new FileReader();
                reader.onload = () => onSuccess(reader.result);
                reader.onerror = () => onError("Error loading"+file.name);
                reader.readAsDataURL(file)
                // EasyMDE.drawUploadedImage(easyMDE)           
            }
        })

It would be nice to have a working example of the imageUploadFunction.

Ionaru commented 10 months ago

Yeah: https://github.com/Ionaru/easy-markdown-editor/issues/334

Underest commented 10 months ago

Yes, but as I sad in my question the code from #334 is not working.

Lunedor commented 7 months ago

All code samples I found that has same issue but finally I made it with flask backend with below codes and working right for me:

app.config['ALLOWED_IMAGES_TYPES'] = ['image/png', 'image/jpeg', 'image/jpg']
app.config['IMAGE_UPLOAD_FOLDER'] = 'static/images'  # or any other folder you want to use for image uploads
app.config['IMAGE_MAX_SIZE'] = 1024 * 1024 * 2  # 2 MB

@app.route('/imageUpload', methods=['POST'])
def upload_image():
    """
    Upload an image to the server and store it to the folder defined in
    IMAGE_UPLOAD_FOLDER in flask configuration.
    Note that the image folder must be created first and with write access.
    :return: A JSON response with the expected format for EasyMDE.
    """
    # Check if the request contains the 'image' field in FormData
    if 'image' not in request.files:
        return jsonify({'error': 'noFileGiven'}), 400  # Bad request

    file = request.files['image']

    if file.filename == '':
        return jsonify({'error': 'noFileGiven'}), 400  # Bad request

    if file and file.content_type in app.config['ALLOWED_IMAGES_TYPES']:
        if file.content_length > app.config['IMAGE_MAX_SIZE']:
            return jsonify({'error': 'fileTooLarge'}), 413  # Payload Too Large

        # Generate a safe filename
        file_name = f"{file.filename.split('.')[0]}_{len(os.listdir(app.config['IMAGE_UPLOAD_FOLDER']))}.{file.filename.split('.')[-1]}"
        file_path = os.path.join(app.config['IMAGE_UPLOAD_FOLDER'], file_name)

        # Save the file
        file.save(file_path)

        # Construct the response in the expected format for EasyMDE
        image_url = url_for('static', filename=f'images/{file_name}')
        response_data = {
            'data': {
                'filePath': image_url
            }
        }

        return jsonify(response_data), 200, {'Content-Type': 'application/json'}
    else:
        return jsonify({'error': 'typeNotAllowed'}), 415  # Unsupported Media Type

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_IMAGES_TYPES']

and JavaScript part:

function initializeEasyMDE() {
    easyMDE = new EasyMDE({
        element: document.getElementById('editor'),
        autofocus: true,
        spellChecker: false,
        uploadImage: true,
        imageUploadEndpoint: "imageUpload",
        status: [
        "words",
        "upload-image",
        ],
        toolbar: ["bold", "italic", "heading", "|", "quote", "unordered-list", "ordered-list", "|", "link", "image", "|", "preview", "side-by-side", "fullscreen"],
    });
    return easyMDE;
}
bilogic commented 6 months ago

@Lunedor were you able to have an indicator while uploading? Like how GitHub shows ![Uploading image.png…]() and then replace it with the actual link moments later?

Lunedor commented 6 months ago

@bilogic No I haven't seen something like that or try to do make it, I just make some arrangements for resizing image that's all maybe you can use same logic to achieve this one, You can check my repo here: https://github.com/Lunedor/The_Writer

steinhaug commented 2 months ago

Have a look at my setup, this one is working. Notice that I use another build for the JS file used for the include.

https://github.com/Ionaru/easy-markdown-editor/issues/594#issuecomment-2312195816