作上传图片的功能以前,要明白files的方法javascript
文件对象: request.FILES.get() # 获取上传的文件对象css
文件对象.name # 就是文件名 html
文件对象.size # 就是文件字节java
文件对象.chunks() # 这个方法里面存放了上传的文件内容web
form 表单里面要添加一个特殊的参数 enctype="multipart/form-data" # 文件的传输配置django
在a.html内添加一个表单,代码以下json
在BlogA下的urls配置路径api
在BlogA下的views添加函数服务器
在blog中新建一个file文件夹网络
如今咱们能够作上传功能了
富文本编辑功能
首先下载富文本编辑器并解压
下载连接: http://ueditor.baidu.com/website/download.html#ueditor
在static下新建一个名为ueditor的文件夹,并将解压后的ueditor里的文件所有复制粘贴到ueditor文件夹中
将unditor/jsp/config.json文件复制粘贴到跟目录下
在blog下新建一个uecontroller.py,写入如下代码
from django.shortcuts import render , redirect , reverse , HttpResponse import json import re configStr = "" with open('config.json','r',encoding="utf-8") as jf: for line in jf: configStr += re.sub(r"/\*(.*)\*/","",line) print('configStr---',configStr) config = json.loads(configStr) print('config===',config) from django.http import HttpResponse import codecs import json import os from django.views.decorators.csrf import csrf_exempt import random from datetime import * import blog.settings as settings #ROOT = os.path.dirname(__file__) ROOT = settings.BASE_DIR #本地上传图片时构造json返回值 class JsonResult(object): def __init__(self,state="未知错误",url="",title="",original="",error="null"): super(JsonResult,self).__init__() self.state = state self.url = url self.title = title self.original = original self.error = error #构造返回json def buildJsonResult(result): jsondata = {"state":result.state,"url":result.url,"title":result.title,"original":result.original,"error":result.error} return json.dumps(jsondata) def buildFileName(filename): dt = datetime.now() name,ext = os.path.splitext(filename) return dt.strftime("%Y%m%d%M%H%S{0}{1}".format(random.randint(1,999999),ext)) #读取json文件 def getConfigContent(): return config #上传配置类 class UploadConfig(object): def __init__(self,PathFormat,UploadFieldName,SizeLimit,AllowExtensions,SavePath,Base64,Base64Filename): super(UploadConfig,self).__init__() self.PathFormat = PathFormat self.UploadFieldName = UploadFieldName self.SizeLimit = SizeLimit self.AllowExtensions = AllowExtensions self.SavePath = SavePath self.Base64 = Base64 self.Base64Filename = Base64Filename #获取json配置中的某属性值 def GetConfigValue(key): config = getConfigContent() return config[key] #检查文件扩展名是否在容许的扩展名内 def CheckFileType(filename,AllowExtensions): exts = list(AllowExtensions) name,ext = os.path.splitext(filename) return ext in exts def CheckFileSize(filesize,SizeLimit): return filesize<SizeLimit #处理上传图片、文件、视频文件 @csrf_exempt def uploadFile(request,config): result = JsonResult() if config.Base64: pass else: buf = request.FILES.get(config.UploadFieldName) filename = buf.name if not CheckFileType(filename,config.AllowExtensions): result.error =u"不容许的文件格式" return HttpResponse(buildJsonResult(result)) if not CheckFileSize(buf.size,config.SizeLimit): result.error = u"文件大小超出服务器限制" return HttpResponse(buildJsonResult(result)) try: truelyName = buildFileName(filename) webUrl = config.SavePath+ truelyName print(webUrl) #!!!!!!!!!!!! savePath =ROOT+webUrl # savePath =ROOT+webUrl print(savePath) f = codecs.open(savePath,"wb+") for chunk in buf.chunks(): f.write(chunk) f.flush() f.close() result.state = "SUCCESS" result.url ='/static/upload/img/'+truelyName# truelyName print('truelyName', truelyName) result.title = truelyName result.original = truelyName response = HttpResponse(buildJsonResult(result)) response["Content-Type"] = "text/plain" return response except Exception as e: result.error = u"网络错误" return HttpResponse(buildJsonResult(result)) #处理在线图片与在线文件 #返回的数据格式:{"state":"SUCCESS","list":[{"url":"upload/image/20140627/6353948647502438222009315.png"},{"url":"upload/image/20140627/6353948659383617789875352.png"},{"url":"upload/image/20140701/6353980733328090063690725.png"},{"url":"upload/image/20140701/6353980745691597223366891.png"},{"url":"upload/image/20140701/6353980747586705613811538.png"},{"url":"upload/image/20140701/6353980823509548151892908.png"}],"start":0,"size":20,"total":6} def listFileManage(request,imageManagerListPath,imageManagerAllowFiles,listsize): pstart = request.GET.get("start") start = pstart==None and int(pstart) or 0 psize = request.GET.get("size") size = psize==None and int(GetConfigValue(listsize)) or int(psize) localPath = ROOT+imageManagerListPath filelist = [] exts = list(imageManagerAllowFiles) index = start print(localPath) for imagename in os.listdir(localPath): name,ext = os.path.splitext(imagename) if ext in exts: filelist.append(dict(url=imagename)) index+=1 if index-start>=size: break jsondata = {"state":"SUCCESS","list":filelist,"start":start,"size":size,"total":index} return HttpResponse(json.dumps(jsondata)) #返回配置信息 def configHandler(request): content = getConfigContent() callback = request.GET.get("callback") if callback: return HttpResponse("{0}{1}".format(callback,json.dumps(content))) return HttpResponse(json.dumps(content)) #图片上传控制 @csrf_exempt def uploadimageHandler(request): AllowExtensions = GetConfigValue("imageAllowFiles") PathFormat = GetConfigValue("imagePathFormat") SizeLimit = GetConfigValue("imageMaxSize") UploadFieldName = GetConfigValue("imageFieldName") SavePath = GetConfigValue("imageUrlPrefix") upconfig = UploadConfig(PathFormat,UploadFieldName,SizeLimit,AllowExtensions,SavePath,False,'') return uploadFile(request,upconfig) def uploadvideoHandler(request): AllowExtensions = GetConfigValue("videoAllowFiles") PathFormat = GetConfigValue("videoPathFormat") SizeLimit = GetConfigValue("videoMaxSize") UploadFieldName = GetConfigValue("videoFieldName") SavePath = GetConfigValue("videoUrlPrefix") upconfig = UploadConfig(PathFormat,UploadFieldName,SizeLimit,AllowExtensions,SavePath,False,'') return uploadFile(request,upconfig) def uploadfileHandler(request): AllowExtensions = GetConfigValue("fileAllowFiles") PathFormat = GetConfigValue("filePathFormat") SizeLimit = GetConfigValue("fileMaxSize") UploadFieldName = GetConfigValue("fileFieldName") SavePath = GetConfigValue("fileUrlPrefix") upconfig = UploadConfig(PathFormat,UploadFieldName,SizeLimit,AllowExtensions,SavePath,False,'') return uploadFile(request,upconfig) #在线图片 def listimageHandler(request): imageManagerListPath = GetConfigValue("imageManagerListPath") imageManagerAllowFiles = GetConfigValue("imageManagerAllowFiles") imagelistsize = GetConfigValue("imageManagerListSize") return listFileManage(request,imageManagerListPath,imageManagerAllowFiles,imagelistsize) #在线文件 def ListFileManagerHander(request): fileManagerListPath = GetConfigValue("fileManagerListPath") fileManagerAllowFiles = GetConfigValue("fileManagerAllowFiles") filelistsize = GetConfigValue("fileManagerListSize") return listFileManage(request,fileManagerListPath,fileManagerAllowFiles,filelistsize) actions = { "config":configHandler, "uploadimage":uploadimageHandler, "uploadvideo":uploadvideoHandler, "uploadfile":uploadfileHandler, "listimage":listimageHandler, "listfile":ListFileManagerHander } @csrf_exempt def handler(request): action = request.GET.get("action") return actions.get(action)(request)
ueditor/_examples/submitFormDemo.html里有各类表单样式,咱们选取其中的提交表单的Demo,打开看一下源代码
将其中的script代码拿过来粘贴到fabu.html中并进行修改:
将ueditor/server/editor_api.js中baseURL修改为咱们的路径
修改blog下urls.py
因为小步骤太多,直接上传修改完成后的fabu.html代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <script type="text/javascript" charset="utf-8" src="/static/ueditor/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="/static/ueditor/_examples/editor_api.js"></script> <style type="text/css"> body{ font-size:14px; } </style> </head> <body> <h1>欢迎{{ user.username }}发布博客...</h1> <span style="color: red">{{ msg }}</span> <form action="/BlogA/fabu" method="post"> {% csrf_token %} <p>标题:<input name="title" type="text" style="width: 500px"></p> <p>内容:<textarea id="myEditor" name="context" style="width: 500px;height: 300px"> </textarea></p> <p><input type="submit" value="确认发布"></p> </form> <script type="text/javascript"> var editor_a = UE.getEditor('myEditor',{initialFrameHeight:500, serverUrl:'/uecontroller' } ); </script> </body> </html>
操做完成后咱们刷新网页
若有错误之处,欢迎评论指出