为了在Django框架下使用Xheditor上传图片,竟然折腾了我一个晚上。期间也遇到种种问题,网上相关资料极少。如今把经验分享给你们。javascript
1.下载http://xheditor.com/html
2.将其中的xheditor-zh-cn.min.js以及xheditor_emot、xheditor_plugins和xheditor_skin三个文件夹copy到xheditor目录下。注:若是您网站中没有使用jQuery框架,也请一并上传jquery文件夹中的jquery-1.4.4.min.jshtml5
(上传文件域名字为:filedata
返回结构必需为json,而且结构以下:{"err":"","msg":"200906030521128703.gif"})java
3.在相应html文件的</head>以前添加jquery
<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代码里加上: chrome
<script type="text/javascript"> $(function(){ $('#txt_notes').xheditor({width:'800',height:'300',upImgUrl:"/admin/upload/",upImgExt:"jpg,jpeg,gif,png"}); }) </script>
先看下项目的结构图django
1.settings.py配置json
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.上传主要代码post
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))