zl程序教程

您现在的位置是:首页 >  其他

当前栏目

bbs项目富文本编辑器实现上传文件到media目录详解编程语言

文件上传项目编程语言 实现 详解 目录 文本编辑
2023-06-13 09:11:54 时间

media目录是在project的settings中设置的,static目录是django自己使用的静态文件的上传目录,media目录是用户自定义上传文件的目录

# Django用户上传的文件都放在media目录下 

MEDIA_URL = "/media/" 

MEDIA_ROOT = os.path.join(BASE_DIR,"media") 

我们这样设置了,django还是找不到我们的media目录,还需要在路由系统系统设置,我们这里在django的一级路由中设置

首先需要导入2个模块

from django.conf import settings 

from django.views.static import serve 

然后定义路由映射的关系,这个是固定写法

url(r^media/(?P path .*)$, serve, {"document_root": settings.MEDIA_ROOT}), 

然后我们就可以使用media目录存储我们上次的文件,django就可以找到这个目录下的文件了

先看下我们的富文本编辑器

 !DOCTYPE html 

 html lang="en" 

 head 

 meta charset="UTF-8" 

 title Title /title 

 link rel="stylesheet" href="/static/css/bootstrap-theme.css" 

 /head 

 body 

 h2 {{ auther }}个人博客站点管理后台 /h2 

 h3 文章标题 /h3 

 form method="post" enctype="multipart/form-data" action="" 

 {% csrf_token %} 

 label for="article_id" /label input type="text" id="article_id" placeholder="文章标题" name="new_article_name" 

 h3 文章内容 /h3 

 textarea name="new_article_content" cols="70" rows="20" id="editor_id" 

 /textarea 

 input type="submit" value="提交" 

 /form 

 script src="/static/jq/jquery-3.3.1.js" /script 

 script charset="utf-8" src="/static/kindeditor/kindeditor-all.js" /script 

{# script charset="utf-8" src="/static/kindeditor/lang/zh-CN.js" /script #} 

 script 

 KindEditor.ready(function(K) { 

 window.editor = K.create(#editor_id,{ 

 width : 1200px, 

 item:[ 

 source, |, undo, redo, |, preview, print, template, code, cut, copy, paste, 

 plainpaste, wordpaste, |, justifyleft, justifycenter, justifyright, 

 justifyfull, insertorderedlist, insertunorderedlist, indent, outdent, subscript, 

 superscript, clearhtml, quickformat, selectall, |, fullscreen, /, 

 formatblock, fontname, fontsize, |, forecolor, hilitecolor, 

 italic, underline, strikethrough, lineheight, removeformat, |, image, multiimage, 

 flash, media, insertfile, table, hr, emoticons, baidumap, pagebreak, 

 anchor, link, unlink, |, about 

 uploadJson:"/app1/upload/", 

 extraFileUploadParams:{ 

 csrfmiddlewaretoken:$("[name=csrfmiddlewaretoken]").val() 

 filePostName:"upload_img" 

 }); 

 }); 

 /script 

 /body 

 /html 

前端的效果是

bbs项目富文本编辑器实现上传文件到media目录详解编程语言

 这里我们点击上传文件,看下后台的视图函数的处理,把上传的文件写到media目录中,然后把写的图片的地址返回到前端,富文本编辑器就会去找media中找到对应的路径,然后渲染到前台页面上

from bbs import settings 

from django.http import JsonResponse 

import os 

def upload(request): 

 print(settings.MEDIA_ROOT,type(settings.MEDIA_ROOT)) 

 file_obj = request.FILES.get("upload_img") 

 upload_path = os.path.join(settings.MEDIA_ROOT,"upload",file_obj.name) 

 with open(upload_path,"wb") as f: 

 for line in file_obj: 

 f.write(line) 

 res={ 

 "error":0, 

 "url":"/media/upload/"+file_obj.name