Giter Site home page Giter Site logo

Comments (5)

Ionaru avatar Ionaru commented on June 14, 2024

Yeah: #334

from easy-markdown-editor.

Underest avatar Underest commented on June 14, 2024

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

from easy-markdown-editor.

Lunedor avatar Lunedor commented on June 14, 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;
}

from easy-markdown-editor.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.