运用Django、MySQL、HTML、JS、Ajax模拟开发博客系统(6)

做上传图片的功能之前,要明白files的方法

      文件对象: request.FILES.get()     # 获取上传的文件对象

      文件对象.name              # 就是文件名       

      文件对象.size             # 就是文件字节

      文件对象.chunks()           # 这个方法里面存放了上传的文件内容

      form 表单里面要添加一个特殊的参数  enctype="multipart/form-data" # 文件的传输配置

在a.html内添加一个表单,代码如下

  • 155822_Qhe3_3764483.png

在BlogA下的urls配置路径

  • 155914_TWR5_3764483.png

在BlogA下的views添加函数

  •     160053_CGfM_3764483.png

在blog中新建一个file文件夹

  • 160238_D5AT_3764483.png
  • 160246_F0C1_3764483.png

现在我们可以做上传功能了

  • 160443_9EuU_3764483.png
  • 160449_fO5r_3764483.png

富文本编辑功能

首先下载富文本编辑器并解压

下载链接:  http://ueditor.baidu.com/website/download.html#ueditor

 

  • 161233_TabP_3764483.png

在static下新建一个名为ueditor的文件夹,并将解压后的ueditor里的文件全部复制粘贴到ueditor文件夹中

  • 161814_Hb5O_3764483.png

将unditor/jsp/config.json文件复制粘贴到跟目录下

  • 163526_ezPD_3764483.png
  • 163532_SaYV_3764483.png

在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中并进行修改:

  • 165735_x1eu_3764483.png
  • 165827_BlZQ_3764483.png
  • 171854_ikjf_3764483.png

将ueditor/server/editor_api.js中baseURL修改成我们的路径

  • 172934_YoRV_3764483.png

修改blog下urls.py

  • 174714_8Jof_3764483.png

由于小步骤太多,直接上传修改完成后的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>

操作完成后我们刷新网页

  • 180145_jmb5_3764483.png

如有错误之处,欢迎评论指出

 

 

转载于:https://my.oschina.net/u/3764483/blog/1811650

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值