zoukankan      html  css  js  c++  java
  • 万里长征第二步——django个人博客(第七步 ——上传文件)

    1. 在项目目录下新建一个 ‘uploads’文件夹以保存上传的文件
    2. 配置setting.py文件
      MEDIA_URL = '/uploads/'
      
      MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads')  #设置上传的绝对路径
    3. 配置urls.py文件,设置路由
      from django.conf.urls import url,include
      from django.contrib import admin
      from django.conf import settings
      
      urlpatterns = [
          url(r'^uploads/(?P<path>.*)$',  
      'django.views.static.serve', 
                      {'document_root': settings.MEDIA_ROOT,}),
          url(r'^admin/', admin.site.urls),
          url(r'^todolist/',include('todolist.urls')),
      ]
    4. 为富文本编辑器设置上传文件
      1. 在APP目录下创建配置文件‘upload.py’
        # -*- coding: utf-8 -*-
        from django.http import HttpResponse
        from django.conf import settings
        from django.views.decorators.csrf import csrf_exempt
        import os
        import uuid
        import json
        import datetime as dt
        
        @csrf_exempt
        def upload_image(request, dir_name):
        ##################
            #  kindeditor图片上传返回数据格式说明:
            # {"error": 1, "message": "出错信息"}
            # {"error": 0, "url": "图片地址"}
            ##################
        result = {"error": 1, "message": "上传出错"}
            files = request.FILES.get("imgFile", None)
        if files:
                result =image_upload(files, dir_name)
        return HttpResponse(json.dumps(result), content_type="application/json")
        
        #目录创建
        def upload_generation_dir(dir_name):
            today = dt.datetime.today()
            dir_name = dir_name + '/%d/%d/' %(today.year,today.month)
        if not os.path.exists(settings.MEDIA_ROOT + dir_name):
                os.makedirs(settings.MEDIA_ROOT + dir_name)
        return dir_name
        
        # 图片上传
        def image_upload(files, dir_name):
        #允许上传文件类型
        allow_suffix =['jpg', 'png', 'jpeg', 'gif', 'bmp']
            file_suffix = files.name.split(".")[-1]
        if file_suffix not in allow_suffix:
        return {"error": 1, "message": "图片格式不正确"}
            relative_path_file = upload_generation_dir(dir_name)
            path=os.path.join(settings.MEDIA_ROOT, relative_path_file)
        if not os.path.exists(path): #如果目录不存在创建目录
        os.makedirs(path)
            file_name=str(uuid.uuid1())+"."+file_suffix
            path_file=os.path.join(path, file_name)
            file_url = settings.MEDIA_URL + relative_path_file + file_name
        open(path_file, 'wb').write(files.file.read())
        return {"error": 0, "url": file_url}
      2. 为富文本编辑器设置路由。urls.py
        from django.conf.urls import url
        from django.contrib import admin
        from blog.views import index
        from django.conf import settings
        from blog.upload import upload_image
        
        urlpatterns = [
            url(r'^uploads/(?P<path>.*)$',
        'django.views.static.serve',
                {'document_root': settings.MEDIA_ROOT,}),
            url(r'^admin/upload/(?P<dir_name>[^/]+)$', upload_image, name='upload_image'),
            url(r'^admin/', admin.site.urls),
            url(r'^$', index, name='index')
        ]
      3. 配置KindEditor,在config.js文件中
        KindEditor.ready(function(K) {
           K.create('textarea[name="content"]', {
                  width : "800px",
                   height : "200px",
                  uploadJson: '/admin/upload/kindeditor',
           });
        });
  • 相关阅读:
    博客园开通新随笔
    遍历两个数组,并输出数组中的不同内容
    1021-二叉树复制和左右子树互换
    1020-层次遍历二叉树
    1019-计算二叉树的高度和结点数
    1018-深度遍历二叉树
    1017-乘积最大
    1016-求幂
    1015-最大公约数和最小公倍数
    1014-数据的插入与删除
  • 原文地址:https://www.cnblogs.com/ymjr/p/5554825.html
Copyright © 2011-2022 走看看