上篇博客介绍到如何给Flask项目加上TinyMCE编辑器
这篇就给大家讲讲如何用TinyMCE的插件上传图片的七牛
首先申请七牛的云储存空间
需要找到几样东西
- ACCESS_KEY
- SECRET_KEY
- BUCKET_NAME(上传空间名字)
- DOMAIN_NAME(外链域名)
需要下载一个TinyMCE的插件
https://github.com/jkgeekJack/tinymce-imageupload
拷贝到之前项目的tinymce/js/tinymce/plugins目录下
在之前那个tinymce_setup.js加上这个补丁的名字和上传图片的地址
在plugins和toolbar加上imageupload
tinymce.init({
selector: '#content',
directionality:'ltr',
language:'zh_CN',
height:400,
plugins: [
'advlist autolink link image lists charmap print preview hr anchor pagebreak spellchecker',
'searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking',
'save table contextmenu directionality emoticons template paste textcolor',
'codesample imageupload',
],
toolbar: 'insertfile undo redo | \
styleselect | \
bold italic | \
alignleft aligncenter alignright alignjustify | \
bullist numlist outdent indent | \
link image | \
print preview media fullpage | \
forecolor backcolor emoticons |\
codesample fontsizeselect fullscreen| \
imageupload',
fontsize_formats: '10pt 12pt 14pt 18pt 24pt 36pt',
nonbreaking_force_tab: true,
//上传图片的地址
imageupload_url: 'submit-image',
});
这个插件还需要依赖jquery
到该网站下载,将jquery-xxx.min.js放进static/js的下
http://jquery.com/download/
在原来的页面上引用jquery
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="{{ url_for('static', filename='tinymce/js/tinymce/tinymce.min.js') }}"></script>
<script src="{{ url_for('static', filename='js/tinymce_setup.js') }}"></script>
{# 引用jquery#}
<script src="{{ url_for('static', filename='js/jquery-2.2.3.min.js') }}"></script>
</head>
<body>
<form method="post" action="">
<input class="editor" name="content" id="content">
<button type="submit">提交</button>
</form>
</body>
</html>
现在可以获取到图片,接下来是将图片上传到七牛
首先要安装七牛的库
pip install qiniu
接下来编写逻辑
from flask import request
from qiniu import Auth
route('/submit-image', methods=['GET', 'POST'])
def submitImage():
file = request.files['file']
# 上传到七牛后保存的文件名
key=str(int(time.time()))+file.filename
# print file.filename
access_key = 'your access key'
secret_key = 'your secret key'
# 构建鉴权对象
q = Auth(access_key, secret_key)
# 要上传的空间
bucket_name = 'your bucket name'
#http://+外链域名
domian_name = 'your domain name'
# 生成上传 Token,可以指定过期时间等
token = q.upload_token(bucket_name, key, 3600)
ret, info = _form_put(token, key, file.read(),params=None,
mime_type='application/octet-stream', crc=None)
print(info)
print ret['key']
return '{"error":false,"path":"'+domian_name+key+'"}'
效果图
这里写图片描述这里写图片描述
网友评论