博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
django实现目录上传(最简单的方法)
阅读量:7043 次
发布时间:2019-06-28

本文共 1574 字,大约阅读时间需要 5 分钟。

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

转载地址:http://kghal.baihongyu.com/

你可能感兴趣的文章
对JAVA集合进行遍历删除时务必要用迭代器
查看>>
poj 2010 Moo University - Financial Aid(优先队列(最小堆)+ 贪心 + 枚举)
查看>>
统计多少个汉字与字母
查看>>
Odoo9发行说明
查看>>
logging日志管理--将日志打印在屏幕上
查看>>
PF_NETLINK应用实例NETLINK_KOBJECT_UEVENT具体实现--udev实现原理
查看>>
mongodb 3.x 之实用新功能窥看[2] ——使用$lookup做多表关联处理
查看>>
实际利率 > 名义利率
查看>>
第三篇:基于K-近邻分类算法的手写识别系统
查看>>
9.6智力题(一)——给定两条绳子,每条绳子燃烧殆尽正好用一个小时,用这两条绳子准确计时15分钟...
查看>>
启动redis
查看>>
Swift 互斥锁写法
查看>>
matlab中元胞数组的创建与内容读取
查看>>
P3390 【模板】矩阵快速幂
查看>>
DateFormatUtil格式化时间
查看>>
RPi 2B QEMU 模拟树莓派
查看>>
Asp.net Web Api开发(第四篇)Help Page配置和扩展
查看>>
Microsoft Visual C++ 9.0 is required Unable to find vcvarsall.bat 解决办法
查看>>
【转】ASP.NET中验证控件的使用
查看>>
搭建和测试 Redis 主备和集群
查看>>