1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
HTML代码:
<!DOCTYPE html>
<
html
lang
=
"en"
>
<
head
>
<
meta
charset
=
"UTF-8"
>
<
title
>Title</
title
>
</
head
>
<
body
>
<
form
enctype
=
"multipart/form-data"
action
=
"/upload/"
method
=
"POST"
>
{% csrf_token %}
<
input
type
=
"file"
name
=
"upload"
id
=
"file_input"
multiple
webkitdirectory
=
""
>
<
br
/>
<
input
type
=
"submit"
value
=
"上传"
/>
</
form
>
</
body
>
</
html
>
|
1
2
3
4
5
|
url.py
urlpatterns
=
[
url(r
'^upload/'
,upload)
]
|
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
|
views.py
# -*- coding: utf-8 -*-
from
__future__
import
unicode_literals
from
django.shortcuts
import
render
from
django.http
import
HttpResponse
from
django.http
import
HttpResponseRedirect
import
os
import
sys
reload
(sys)
sys.setdefaultencoding(
'utf8'
)
# Create your views here.
def
upload(request):
if
request.method
=
=
'GET'
:
return
render(request,
'index.html'
)
elif
request.method
=
=
'POST'
:
dir
=
request.FILES
dirlist
=
dir
.getlist(
"upload"
,
None
)
#获取文件列表
if
not
dirlist:
return
HttpResponse(
"没有上传内容"
)
else
:
for
file
in
dirlist:
position
=
os.path.join(
'C:\\Users\\huyuan\\Desktop\\test\\upload'
,
str
(
file
))
# 获取上传文件的文件名,并将其存储到指定位置
storage
=
open
(position,
'wb+'
)
# 打开存储文件
for
chunk
in
file
.chunks():
# 分块写入文件
storage.write(chunk)
storage.close()
#写入完成后关闭文件
return
HttpResponse(
"上传成功"
)
# 返回客户端信息
else
:
return
HttpResponseRedirect(
"不支持的请求方法"
)
|
这种方式上传目录无法保持目录结构,只会把目录和其子目录的文件上传而不会上传目录
本文转自 红尘世间 51CTO博客,原文链接:http://blog.51cto.com/hongchen99/1967802