给Django后台富文本编辑器添加上传文件的功能
使用富文本编辑器上传的文件是要放到服务器上的,所以这是一个request。既然是一个request,就需要urls.py进行转发请求views.py进行处理。views.py处理完了返回一个文件所在的路径给富文本编辑器,富文本编辑器通过HTML来渲染文件,如果文件是图片,就显示图片。
以下以simditor富文本编辑器为例。它上传文件的api是这样的:
#upload要么为false 要么为对象
upload:{
url: '',
params: null,
fileKey: 'upload_file',
connectionCount: 3,
leaveConfirm: 'Uploading is in progress, are you sure to leave this page?'
}
需要返回的JSON格式:
{
"success": true/false,
"msg": "error message", # optional
"file_path": "[real file path]"
}
第1步:在settings.py建立MEDIA的全局变量
#settings.py
MEDIA_URL='/uploads/'
MEDIA_ROOT=os.path.join(BASE_DIR,'uploads')
第2步:配置富文本编辑器JS文件
upload:{
url:'/myadmin/upload/files', /* 注意myadmin前面的斜杠不能省掉,这是相对于根目录的*/
filekey:'upload_file', /* 相当于html标签里面的name值 */
}
第3步:配置urls.py
#urls.py
from blog.upload_proc import upload_file
urlpatterns+=[
url(r'^myadmin/upload/(?P<dir_name>)',upload_file)
]
第4步:撰写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")
第5步:再次配置urls.py
为什么需要再次配置urls.py
呢?因为文本编辑器虽然返回了已经上传的文件的地址,但是要显示在页面上,实际上又是一次request。凡是request
,都需要urls.py
转发给views.py
进行处理。
#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})
]
扩展:一次性上传多个文件,如上传多张图片
- simditor采用的方法是利用ajax请求多次,有几个文件就请求几次。
- 有没有其他的方法呢?