django 发帖时碰到的图片上传

所用编辑器 【wangEditor.js】 

图片上传接口 '/edit/image/' 返回内容  参照 https://www.kancloud.cn/wangfupeng/wangeditor3/335782

 # 2018_12_29 日更新

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>wangEditor demo</title>
</head>
  <script type="text/javascript">
function modifyContent() {
var introduce = document.getElementById("introduce");
introduce.value = editor.txt.html();
}
</script>

<body>
<form action="" method="post" onsubmit="modifyContent()">
<div>
<!-- 编辑器编辑,提交时执行js,获得编辑器的内容,赋值给textarea,用于向后台提交存入数据库 -->
<textarea rows="5" cols="35" name="usIntroduce" style="display:none;" id="introduce"></textarea>
<div id="editor">
{#        <p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p>#}
        <p>欢迎使用 <b>wangEditor</b> 富文本编辑器</p><p><img src="/static/upload/cart.png" style="max-100%;"></p>
</div>
        <!-- 注意, 只需要引用 JS,无需引用任何 CSS !!!-->
        <script type="text/javascript" src="/static/wangEditor.js"></script>
        <!-- 设置全屏功能的两个js文件,先引入jquery-3.2.1.min.js,在引入wangEditor-fullscreen-plugin.js -->
       
        <script type="text/javascript">
            var E = window.wangEditor
            var editor = new E('#editor')
            /* 处理上传图片的controller路径 */
             editor.customConfig.uploadImgServer = '/edit/image/'


                                                                                                        /* 定义上传图片的默认名字 */
             editor.customConfig.uploadFileName = 'myFileName'
            // 或者 var editor = new E( document.getElementById('editor') )
            editor.create()
            //初始化全屏插件
        </script>
</div> 
<input type="submit" value="提交"></input>
    {% csrf_token %}
</form>

</body>
</html>
View Code---前端代码
from django.shortcuts import render,HttpResponse
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from suibi1.settings import upload_img
import os
# Create your views here.
def index(request):
    if request.method=='GET':
        return render(request,'index.html')
    elif request.method=="POST":
        print(request.POST.get('usIntroduce'))
        return HttpResponse('提交成功')

@csrf_exempt
def image(request):
    if request.method=="POST":
        a = request.FILES['myFileName']
        name = a.name
        with open(os.path.join(upload_img,name),'wb') as f:
            f.write(a.file.read())
            print('图片写入成功')
            return JsonResponse({"errno": 0, "data":[os.path.join('/static/upload',name),]})
View Code--django_views

 

原文地址:https://www.cnblogs.com/Skyda/p/10197497.html