Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
Underest opened this issue Dec 19, 2023 · 5 comments · May be fixed by #580
Open

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

Underest opened this issue Dec 19, 2023 · 5 comments · May be fixed by #580
Labels

Comments

@Underest
Copy link

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
Copy link
Owner

Ionaru commented Dec 21, 2023

Yeah: #334

@Underest
Copy link
Author

Underest commented Jan 2, 2024

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

@ppodds ppodds linked a pull request Feb 16, 2024 that will close this issue
5 tasks
@Lunedor
Copy link

Lunedor commented Apr 7, 2024

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
Copy link

bilogic commented May 4, 2024

@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
Copy link

Lunedor commented May 4, 2024

@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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants