article

Monday, December 21, 2020

TinyMCE Upload Image with Python Flask and Jquery Ajax

 


TinyMCE Upload Image with Python Flask and Jquery Ajax

TinyMCE is a well known WYSIWYG HTML Editor which extensively used in web applications to create HTML contents. It supports text formatting, table insert, link insert, image insert and more features.

Download from website https://www.tiny.cloud/


app.py
#app.py
from flask import Flask, render_template, jsonify, request
from werkzeug.utils import secure_filename
import os
#import magic
import urllib.request

app = Flask(__name__)

UPLOAD_FOLDER = 'static/uploads'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
  
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])
  
def allowed_file(filename):
 return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
 
@app.route('/')
def main():
    return render_template('index.html')
 

@app.route("/upload",methods=["POST","GET"])
def upload():  
    if request.method == 'POST':
        file = request.files['file']
        filename = secure_filename(file.filename)
         
        if file and allowed_file(file.filename):
           file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
           print('File successfully uploaded ' + file.filename + ' to static/upload')
        else:
           print('Invalid Uplaod only png, jpg, jpeg, gif')   
    return jsonify(filename)
	
if __name__ == '__main__':
    app.run(debug=True)
templates/index.html
//templates/index.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>TinyMCE Upload Image with Python Flask and Jquery Ajax</title> 
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
</head>
<body class="">
<div class="container">	
	<div class="row">	
		<h2>TinyMCE Upload Image with Python Flask and Jquery Ajax</h2>				
		<form id="posts" name="posts" method="post">
			<textarea name="message" id="message"></textarea><br>				
		</form>		
	</div>	
</div>
<script src="/static/tinymce/tinymce.min.js"></script>
<script>
tinymce.init({
	selector: "textarea",
	plugins: "code",
	toolbar: "undo redo | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link code image_upload",
	menubar:false,
    statusbar: false,
	content_style: ".mce-content-body {font-size:15px;font-family:Arial,sans-serif;}",
	height: 400,
	setup: function(ed) {
		
		var fileInput = $('<input id="tinymce-uploader" type="file" name="pic" accept="image/*" style="display:none">');
		$(ed.getElement()).parent().append(fileInput);
		
		fileInput.on("change",function(){			
			var file = this.files[0];
			var reader = new FileReader();			
			var formData = new FormData();
			var files = file;
			formData.append("file",files);
			formData.append('filetype', 'image');				
			jQuery.ajax({
				url: "/upload",
				type: "post",
				data: formData,
				contentType: false,
				processData: false,
				async: false,
				success: function(response){
					var fileName = response;
					if(fileName) {
						ed.insertContent('<img src="/static/uploads/'+fileName+'"/>');
					}
				}
			});		
			reader.readAsDataURL(file);	 
		});		
		
		ed.addButton('image_upload', {
			tooltip: 'Upload Image',
			icon: 'image',
			onclick: function () {
				fileInput.trigger('click');
			}
		});
	}
});
</script>
</body>
</html>

Related Post