1、配置上传的文件路径
在settings.py中配置MEDIA_URL和MEDIA_ROOT
MEDIA_URL = '/upload/' MEDIA_ROOT = os.path.join(BASE_DIR, 'upload')
2、urls.py中配置路由
url(r"^upload/(?P.*)$", \ "django.views.static.serve", \ {"document_root": settings.MEDIA_ROOT,}),
完成以上两步,Django完成上传文件自定义配置了。文件上传会保存到项目根目录的upload目录下。
接下来完成KindEditor富文本编辑器的文件上传功能
1、修改KindEditor配置文件config.js
配置KindEditor文件上传路径
KindEditor.ready(function(K) { K.create('textarea[name="content"]', { width : "800px", height : "200px", uploadJson: '/admin/upload/kindeditor', }); });
2、编写upload.py
# -*- coding: utf-8 -*- from django.http import HttpResponse from django.conf import settings from django.views.decorators.csrf import csrf_exempt import os import uuid import json import datetime as dt @csrf_exempt def upload_p_w_picpath(request, dir_name): ################## # kindeditor图片上传返回数据格式说明: # {"error": 1, "message": "出错信息"} # {"error": 0, "url": "图片地址"} ################## result = {"error": 1, "message": "上传出错"} files = request.FILES.get("imgFile", None) if files: result =p_w_picpath_upload(files, dir_name) return HttpResponse(json.dumps(result), content_type="application/json") #目录创建 def upload_generation_dir(dir_name): today = dt.datetime.today() dir_name = dir_name + '/%d/%d/' %(today.year,today.month) if not os.path.exists(settings.MEDIA_ROOT + dir_name): os.makedirs(settings.MEDIA_ROOT + dir_name) return dir_name
# 图片上传 def p_w_picpath_upload(files, dir_name): #允许上传文件类型 allow_suffix =['jpg', 'png', 'jpeg', 'gif', 'bmp'] file_suffix = files.name.split(".")[-1] if file_suffix not in allow_suffix: return {"error": 1, "message": "图片格式不正确"} relative_path_file = upload_generation_dir(dir_name) path=os.path.join(settings.MEDIA_ROOT, relative_path_file) if not os.path.exists(path): #如果目录不存在创建目录 os.makedirs(path) file_name=str(uuid.uuid1())+"."+file_suffix path_file=os.path.join(path, file_name) file_url = settings.MEDIA_URL + relative_path_file + file_name print file_url open(path_file, 'wb').write(files.read()) return {"error": 0, "url": file_url}
3、修改url路由
from blog.upload import upload_p_w_picpath url(r'^admin/upload/(?P[^/]+)$', upload_p_w_picpath, name='upload_p_w_picpath'),