django实现目录上传(最简单的方法)

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值