1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
# 配置文件:
# 與用戶上傳相關的配置
MEDIA_ROOT
=
os.path.join(BASE_DIR,
"media"
)
MEDIA_URL
=
"/media/"
# 路由中:
from
django.urls
import
path, re_path
from
django.views.static
import
serve
from
django.conf
import
settings
from
app01
import
views
urlpatterns
=
[
# media配置:
re_path(r
"media/(?P<path>.*)$"
, serve, {
"document_root"
: settings.MEDIA_ROOT}),
# 文本編輯器上傳圖片url
path(
'ke_upload/'
, views.ke_upload),
]
# 模板中:
"""
<div class="form-group">
<label for="content">內容 </label> <!--<textarea name="content" cols="30" rows="10"></textarea>-->
{{ form.content }} <span>{{ form.content.errors.0 }}</span>
</div>
{% block js %}
<script src = "/static/js/jquery-3.2.1.min.js"> </script>
<script charset="utf-8" src="/static/plugins/kindeditor/kindeditor-min.js"></script>
<script charset="utf-8" src="/static/plugins/kindeditor/lang/zh_CN.js"></script>
<script>
// KindEditor 上傳的瞬間,幫你生成iframe+form進行僞Ajax操做
KindEditor.ready(function (K) {
window.editor = K.create('textarea[name="content"]', {
resizeType: 1,
allowPreviewEmoticons: true,
allowImageUpload: true,
items: [
'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline',
'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist',
'insertunorderedlist', '|', 'emoticons', 'image', 'link'],
uploadJson: '/ke_upload/',
//filePostName:"upload_img", //默認是imgFile
extraFileUploadParams:{
"csrfmiddlewaretoken":"{{ csrf_token }}"
}
});
});
</script>
{% endblock %}
"""
# 視圖中:
from
django.shortcuts
import
render, redirect, HttpResponse
import
os
import
time
import
json
def
ke_upload(request):
file_obj
=
request.FILES.get(
'imgFile'
)
# 經過filePostName修改
# 上傳後面的參數kd用的是dir
# upload_img.html?dir=image 說明是圖片
# upload_img.html?dir=media 說明是視頻,
file_type
=
request.GET.get(
'dir'
)
file_obj.name
=
"%s%s"
%
(time.time(), file_obj.name)
file_dir
=
'media%s%s'
%
(os.sep, file_type)
if
not
os.path.exists(file_dir):
os.makedirs(file_dir)
file_path
=
os.path.join(
"media"
, file_type, file_obj.name)
with
open
(file_path,
'wb'
) as f:
for
line
in
file_obj:
f.write(line)
dic
=
{
'error'
:
0
,
'url'
:
'/media/%s/%s'
%
(file_type, file_obj.name),
'message'
:
'錯誤了...'
}
return
HttpResponse(json.dumps(dic))
|