Add the function of uploading files to the Django background rich text editor

Files uploaded using a rich text editor are meant to be placed on the server, so this is a request. Since it is a request, urls.py is required to forward the request views.py for processing. views.py returns the path of a file to the rich text editor after processing. The rich text editor renders the file through HTML. If the file is an image, the image is displayed.

The following takes the simditor rich text editor as an example. Its api for uploading files is like this:

#upload要么为false 要么为对象
upload:{
        url: '', params: null, fileKey: 'upload_file', connectionCount: 3, leaveConfirm: 'Uploading is in progress, are you sure to leave this page?' }

The JSON format that needs to be returned:

{
  "success": true/false,
  "msg": "error message", # optional "file_path": "[real file path]" }

Step 1: Create a global variable for MEDIA in settings.py

#settings.py
MEDIA_URL='/uploads/'
MEDIA_ROOT=os.path.join(BASE_DIR,'uploads')

Step 2: Configure Rich Text Editor JS File

upload:{
        url:'/myadmin/upload/files', /* 注意myadmin前面的斜杠不能省掉,这是相对于根目录的*/
        filekey:'upload_file', /* 相当于html标签里面的name值 */ }

Step 3: Configure urls.py

#urls.py
from blog.upload_proc import upload_file

urlpatterns+=[
   url(r'^myadmin/upload/(?P<dir_name>)',upload_file)
]

Step 4: Write the upload_file handler

#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")

Step 5: Configure urls.py again

Why do you need to configure urls.pyit again? Because although the text editor returns the address of the uploaded file, it is actually another request to be displayed on the page. Anything requestthat needs to be urls.pyforwarded to views.pyfor processing.

#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}) ]

Extension: upload multiple files at one time, such as uploading multiple images

  1. The method used by simditor is to use ajax to request multiple times, and request several times for several files.
  2. Is there any other way?

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325700910&siteId=291194637