[原创]Python/Django使用富文本编辑器XHeditor上传本地图片

前言

为了在Django框架下使用Xheditor上传图片,居然折腾了我一个晚上。期间也遇到种种问题,网上相关资料极少。现在把经验分享给大家。

正文

xheditor篇

1.下载http://xheditor.com/

2.将其中的xheditor-zh-cn.min.js以及xheditor_emot、xheditor_plugins和xheditor_skin三个文件夹copy到xheditor目录下。注:如果您网站中没有使用jQuery框架,也请一并上传jquery文件夹中的jquery-1.4.4.min.js

(上传文件域名字为:filedata
返回结构必需为json,并且结构如下:{"err":"","msg":"200906030521128703.gif"})

3.在相应html文件的</head>之前添加

<script src="/static/js/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="/static/xheditor/xheditor-1.1.14-zh-cn.min.js" type="text/javascript"></script>

4.在您的页面初始JS代码里加上: 

<script type="text/javascript">
$(function(){
    $('#txt_notes').xheditor({'800',height:'300',upImgUrl:"/admin/upload/",upImgExt:"jpg,jpeg,gif,png"});
})
</script>

Python&Django篇

先看下项目的结构图

1.settings.py配置

MIDDLEWARE_CLASSES中注释(否则出现403错误)
 #'django.middleware.csrf.CsrfViewMiddleware',

import os
MEDIA_ROOT = os.path.join(os.path.dirname(__file__),"travels").replace('\','/')

2.urls.py 配置

url(r'^admin/upload/$','wetrip.views.upload.upload_image'),   
url(r'^static/(?P<path>.*)$','django.views.static.serve',  
        {'document_root': "/目录/static/"}),
url(r'^pictures/(?P<path>.*)$','django.views.static.serve',  
        {'document_root': "/目录/travels/pictures"}),

3.上传主要代码

upload.py
#coding=utf-8
from django.http import HttpResponse
from django.utils import simplejson
import time,os
import datetime as dt
import wetrip.settings

#允许上传文件类型
ALLOW_SUFFIX =['.jpg','.png','.jpeg','.gif']
#目录创建
def create_dir():
    today = dt.datetime.today()
    dir_name = '/pictures/%d/%d/%d' %(today.year,today.month,today.day)
    if not os.path.exists(wetrip.settings.MEDIA_ROOT + dir_name):
        os.makedirs(wetrip.settings.MEDIA_ROOT + dir_name)
    return dir_name

def upload_image(request):
    dir_name = create_dir()
    if 'HTTP_CONTENT_DISPOSITION' in request.META:#chrome/firefox Xheditor使用的是Html5方式上传
        disposition = request.META['HTTP_CONTENT_DISPOSITION']
        image_name_suffix = disposition[ disposition.rindex('.') : disposition.rindex('"') ]
        data = request.body #request.raw_post_data#已过时
        return write_data(data,image_name_suffix,dir_name,True)
    else:#普通上传,ie
        if 'filedata' in request.FILES:
            image_name = request.FILES["filedata"].name
            image_name_suffix = image_name[image_name.rindex('.') : ]
            return write_data(request.FILES["filedata"],image_name_suffix,dir_name,False)
        else:
            return HttpResponse(simplejson.dumps({'err':'未选择文件','msg':''},ensure_ascii = False))

#保存图片
def write_data(data,image_name_suffix,dir_name,html5):
    if image_name_suffix in ALLOW_SUFFIX:
            image_name = str(int(time.time())) + image_name_suffix
            try:
                with open(wetrip.settings.MEDIA_ROOT + dir_name+'/'+ image_name,'wb') as destination:
                    if html5:
                        destination.write(data)#写文件流
                    else:
                        for c in data.chunks():
                            destination.write(c)
                return HttpResponse(simplejson.dumps({'err':'','msg':dir_name+'/'+image_name},ensure_ascii = False))
            except Exception,e:
                return HttpResponse(simplejson.dumps({'err':e.message,'msg':''},ensure_ascii = False))
    else:
        return HttpResponse(simplejson.dumps({'err':'上传格式不准确!只支持jpg,png,jpeg,gif','msg':''},ensure_ascii = False))
原文地址:https://www.cnblogs.com/zhxhdean/p/3433678.html