2 富文本的使用
阿新 • • 發佈:2018-09-23
編輯器 middle 圖片 格式 con .py files upload ken
參考 http://kindeditor.net/docs/usage.html
1 下載軟件
2 設置setting.py
STATICFILES_DIRS=[ os.path.join(BASE_DIR,"static"), ] # 告訴djanjo項目用戶上傳的文件保存在哪個目錄下 MEDIA_ROOT = os.path.join(BASE_DIR, "upload") # 告訴用戶用哪個前綴來訪問剛才的定義的那個目錄 MEDIA_URL = "/media/"
3 設置url
# 給用戶上傳的那些文件路徑做認證上傳頭像的 url(r‘^media/(?P<path>.*)‘, serve, {"document_root": settings.MEDIA_ROOT}), # 富文本編輯器裏面上傳的圖片的存放目錄 url(r‘^fault-report/upload-img/$‘, views.upload_img),
# 顯示富文本的頁面 url(r‘^index/$‘, views.index),
4 views設置:
from django.http import JsonResponse # json格式 # Create your views here. # 富文本編輯器上傳圖片的視圖 def upload_img(request):print(request.FILES) res = {"error": 0} # 這是固定寫法,必須用error file_obj = request.FILES.get("imgFile") file_path = os.path.join("upload", "report_images", file_obj.name) # 將文件保存在本地 with open(file_path, "wb") as f: for chunk in file_obj.chunks(): f.write(chunk)# 將上傳文件的url返回給富文本編輯器 res["url"] = "/media/report_images/{}".format(file_obj.name) return JsonResponse(res) def index(request): return render(request, "index.html", locals())
5 在項目裏新建目錄upload,然後再在下面簡歷report_images,這個目錄就是存放上傳的圖片的
6 index頁面設置
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} <div class="form-group"> <label for="content">內容</label> <textarea class="form-control" name="content" id="content" rows="20"></textarea> </div> </form> <script src="/static/jquery-3.3.1.min.js"></script> <script charset="utf-8" src="/static/kindeditor/kindeditor-all-min.js"></script> <script charset="utf-8" src="/static/kindeditor/lang/zh-CN.js"></script> <script> KindEditor.ready(function (K) { window.editor = K.create(‘#content‘, { uploadJson: "/fault-report/upload-img/", extraFileUploadParams: { // 上傳文件時額外傳遞的參數 csrfmiddlewaretoken: $("[name=‘csrfmiddlewaretoken‘]").val(), } }); }); </script> </body> </html>
7 最後就可以上傳圖片了
2 富文本的使用