作上傳圖片的功能以前,要明白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>
操做完成後咱們刷新網頁
若有錯誤之處,歡迎評論指出