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>
url.py urlpatterns = [ url(r‘^upload/‘,upload) ]
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("不支持的请求方法")
这种方式上传目录无法保持目录结构,只会把目录和其子目录的文件上传而不会上传目录
时间: 2024-10-28 11:35:47