django中使用富文本編輯器KindEdito上傳文件/視音頻等資源


參考django中富文本編輯器KindEditor的基本使用

1.在config.js中加入uploadJson,指定上傳請求路徑

如: '/admin/upload/'

KindEditor.ready(function(K) {
        // K.create('textarea[name=content]', {
        K.create('#id_content', {
            width: '800px',
            height: '200px',
            uploadJson: '/admin/upload/',
        });
});

2.添加url和響應函數映射

from .upload import upload
url(r'^admin/upload/$',upload,name="upload"),

3.在settings.py中配置:

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

4.upload函數詳細實現:

#coding=utf-8
import  os
import  uuid
import  json
import  datetime

from django.views.decorators.csrf import csrf_exempt
from django.http import  HttpResponse
from django.conf import settings

'''
@csrf_exempt用於取消csrftoken驗證
url為:http://127.0.0.1:8000/admin/upload/?dir=media post請求
'''
@csrf_exempt
def upload(request):
    '''
    kindeditor圖片上傳返回數據格式說明:
    {"error": 1, "message": "出錯信息"}
    {"error": 0, "url": "圖片地址"}
    '''
    result = {"error": 1, "message": u"上傳失敗"}
    files = request.FILES.get("imgFile", None)  #input type="file" 中name屬性對應的值為imgFile
    type = request.GET['dir']  #獲取資源類型
    if  files:
        result = process_upload(files,type)
    #結果以json形式返回
    return HttpResponse(json.dumps(result),content_type="application/json")


def is_ext_allowed(type,ext):
    '''
    根據類型判斷是否支持對應的擴展名
    '''
    ext_allowed = {}
    ext_allowed['image'] = ['jpg','jpeg', 'bmp', 'gif', 'png']
    ext_allowed['flash'] = ["swf", "flv"]
    ext_allowed['media'] = ["swf", "flv", "mp3", "wav", "wma", "wmv", "mid", "avi", "mpg", "asf", "rm", "rmvb", "mp4"]
    ext_allowed['file'] = ["doc", "docx", "xls", "xlsx", "ppt", "htm", "html", "txt", "zip", "rar", "gz", "bz2", 'pdf']
    return ext in ext_allowed[type]

def get_relative_file_path():
    '''
    獲取相對路徑
    '''
    dt = datetime.datetime.today()
    relative_path = 'upload/%s/%s/' %(dt.year,dt.month)
    absolute_path = os.path.join(settings.MEDIA_ROOT,relative_path)
    print absolute_path
    if not os.path.exists(absolute_path):
        os.makedirs(absolute_path)
    return relative_path


def process_upload(files,type):
    dir_types = ['image','flash','media','file']
    #判斷是否支持對應的類型
    if type not in dir_types:
        return {"error":1, "message": u"上傳類型不支持[必須是image,flash,media,file]"}

    cur_ext = files.name.split('.')[-1]  #當前上傳文件的擴展名
    #判斷是否支持對應的擴展名
    if not is_ext_allowed(type,cur_ext):
        return {'error':1, 'message': u'error:擴展名不支持 %s類型不支持擴展名%s' %(type,cur_ext)}

    relative_path = get_relative_file_path()
    #linux中一切皆文件
    file_name = str(uuid.uuid1()) + "." + cur_ext
    base_name = os.path.join(settings.MEDIA_ROOT,relative_path)
    file_full_path = os.path.join(base_name,file_name).replace('\\','/') #windows中的路徑以\分隔
    file_url = settings.MEDIA_URL + relative_path + file_name

    with open(file_full_path,'wb') as f:
        if  files.multiple_chunks() == False:  #判斷是否大於2.5M
            f.write(files.file.read())
        else:
            for chunk in files.chunks():
                f.write(chunk)


    return {"error": 0, "url": file_url}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM