应用场景
Django下需要加入富文本编辑,使用Tinymce富文本编辑器.但是他的图片上传功能是采用的是网络图片,所以需要加入可以上传本地图片的功能.
Tinymce upload image Demo
前端html:tinymce富文本编辑器,图片功能可以直接选取本地文件
{# 利用jquery来完成form上传等#}
Test
后台views:接受前端post的form,读取input name为'image'的文件.完成以下步骤:
1.读取图片,进行thnmbnail格式化图片大小
2.保存图片,在static/img中 图片保存位置需要用绝对地址
3.返回前台页面,并传输图片保存的url位置
from django.http import HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from PIL import Image
from django.contrib import messages
import os
from django.conf import settings
def index(request):
return render(request, 'index.html')
@csrf_exempt
def upload(request):
try:
file = request.FILES['image']
img = Image.open(file)
img.thumbnail((500, 500), Image.ANTIALIAS)
try:
print(file.name)
img.save('/Users/chaochen/Dropbox/project/env_Django_Demo/tinymce_test/static/img/' + file.name,img.format)
print("img save pass")
except:
print("img.save error")
path = settings.MEDIA_ROOT + file.name
print("upload end")
return HttpResponse(
"" % path)
except Exception:
return HttpResponse("error")
url控制
其中用到了django.view.static函数,必须在setting里面设置好MEDIA_ROOT, STATICFILES_DIRS, STATIC_ROOT
其中比较奇怪的是STATICFILE_DIRS 如果设置到static/img就无法再前端正常读取到图片
STATIC_URL = '/static/'
MEDIA_ROOT = '/static/img/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
`
from django.conf.urls import url
from django.contrib import admin
from . import views
from django.views.static import serve
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index, name='index'),
url(r'upload/$', views.upload, name='upload_img'),
url(r'^static/img/(?P.*)', serve, {'document_root': settings.MEDIA_ROOT})
]
DEMO地址 : https://github.com/orangercat/tinymce_upload_demo
参考文章:[解决tinymce添加本地图片问题](http://blog.csdn.net/tianlanzhixie/article/details/50240071)