使用kindeditor上傳
阿新 • • 發佈:2018-11-28
富文字編輯框的使用,包含使用者的上傳圖片和回顯
1.從官網上下載kindeditor(http://kindeditor.net/doc.php)
<script src="/static/js/kindeditor-all-min.js"></script>
<script src="/static/js/zh-CN.js"></script>
2.html中寫一個textarea文字框
<textarea class="form-control" id="editor_id"></textarea>
#### 3.初始化kindeditor
<script type="text/javascript"> var editor; KindEditor.ready(function(K) { //詳細配置可以參考官方文件 editor = K.create('#editor_id', { //這裡的id 為textarea的ID width : '100%', height:"300px", allowImageUpload : true, uploadJson:"http://127.0.0.1:8005/news_file_upload.html/", extraFileUploadParams:{ csrfmiddlewaretoken:$("[name='csrfmiddlewaretoken']") } , //上傳型別,分別為image、flash、media、file {#dir : "image",#} items : [ 'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste', 'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright', 'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript', 'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/', 'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage', 'flash', 'media', 'insertfile', 'table', 'hr', 'emoticons', 'baidumap', 'pagebreak', 'anchor', 'link', 'unlink', '|', 'about'] }); }); </script>
4.django後臺程式碼
settings.py裡配置
MEDIA_ROOT = os.path.join(BASE_DIR, "news_file") # 我這裡預設上傳到news_file目錄下
urls.py裡配置
from django.views.static import serve
from django.conf import settings
url(r'^news_file/(?P<path>.*)$', serve, {"document_root": settings.MEDIA_ROOT}),
###### 4.1獲取檔案路徑
def createfiles(path):
file_dirs = os.path.join(settings.BASE_DIR,'news_file','imgs',path)
path = os.path.join('news_file/imgs/',path)
if not os.path.exists(path):
os.makedirs(file_dirs)
return path
4.2 檔案上傳
def news_upload(request):
if request.method == 'POST':
item = {}
file = request.FILES.get('imgFile')
print(file.name)
ext_name = file.name.rfind('.')
print(ext_name)
localtime = time.strftime('%Y/%m/%d', time.localtime())
path = createfiles(localtime) + '/'
print(path)
file_name = str(uuid.uuid1()) + file.name
file_path = os.path.join(path, file_name)
print(file_path)
with open(file_path, 'wb') as f:
for temp in file.chunks():
f.write(temp)
item['message'] = '上傳成功'
item['url'] = '/' + file_path
item['error'] = 0
print(item['url'])
return JsonResponse(item)