使用富文本編輯器上傳的文件是要放到服務器上的,因此這是一個request。既然是一個request,就須要urls.py進行轉發請求views.py進行處理。views.py處理完了返回一個文件所在的路徑給富文本編輯器,富文本編輯器經過HTML來渲染文件,若是文件是圖片,就顯示圖片。html
如下以simditor富文本編輯器爲例。它上傳文件的api是這樣的:ajax
#upload要麼爲false 要麼爲對象 upload:{ url: '', params: null, fileKey: 'upload_file', connectionCount: 3, leaveConfirm: 'Uploading is in progress, are you sure to leave this page?' }
須要返回的JSON格式:django
{ "success": true/false, "msg": "error message", # optional "file_path": "[real file path]" }
#settings.py MEDIA_URL='/uploads/' MEDIA_ROOT=os.path.join(BASE_DIR,'uploads')
upload:{ url:'/myadmin/upload/files', /* 注意myadmin前面的斜槓不能省掉,這是相對於根目錄的*/ filekey:'upload_file', /* 至關於html標籤裏面的name值 */ }
#urls.py from blog.upload_proc import upload_file urlpatterns+=[ url(r'^myadmin/upload/(?P<dir_name>)',upload_file) ]
#upload_proc.py from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from django.conf import settings import json import os import datetime @csrf_exempt #取消csrf驗證,不然會有403錯誤 def file_upload(request,dir_name): files=request.FILES.get('upload_file') #獲得文件對象 today=datetime.datetime.today() file_dir=settings.MEDIA_ROOT+dir_name+'/%d/%d/%d/'%(today.year,today.month,today.day) if not os.path.exists(file_dir): os.makedirs(file_dir) file_path=file_dir+files.name open(file_path,'wb+').write(files.read()) #上傳文件 #獲得JSON格式的返回值 upload_info={"success":True,'file_path':settings.MEDIA_URL+files.name} upload_info=json.dumps(upload_info) return HttpResponse(upload_info,content_type="application/json")
爲何須要再次配置urls.py
呢?由於文本編輯器雖然返回了已經上傳的文件的地址,可是要顯示在頁面上,實際上又是一次request。凡是request
,都須要urls.py
轉發給views.py
進行處理。json
#urls.py from django.conf import settings #django.views.static.serve是內置的,可是隻能在開發中使用,生產環境中須要交給服務器來處理,由於上傳的文件已經屬於靜態文件了。 urlpatterns+=[ url(r'^uploads/(?P<path>.*)$',diango.views.static.serve,{'document_root':settings.MEDIA_ROOT}) ]