Django实现文件上传、下载
fileDownloads.py
# 切片读取文件
def file_iterator(filename,chunk_size=512):
with open(filename,'rb') as f:
while True:
c=f.read(chunk_size)
if c:
yield c
else:
break
zip_dir.py
import os
import zipfile
# 如果是文件夹,则压缩文件
def zip_dir(dir_name, zip_file_name):
file_list = []
if os.path.isfile(dir_name):
file_list.append(dir_name)
else:
for root, dirs, files in os.walk(dir_name):
for name in files:
file_list.append(os.path.join(root, name).replace("\\", "/"))
zf = zipfile.ZipFile(os.path.join(dir_name,zip_file_name), "w", zipfile.zlib.DEFLATED)
for tar in file_list:
arc_name = tar[len(dir_name):]
zf.write(tar, arc_name)
zf.close()
一、文件上传
def post(self, request):
# 文件上传
if int(request.data.get("flag", None)) == 3:
File = request.FILES.get("file", None)
mes = redis_resp.hgetall("staff")
mes_username = mes.get("username")
main_type = request.data.get("main_type")
sub_type = request.data.get("sub_type")
if File:
dir = os.path.join(os.path.join(os.path.join(FILE_PATH, mes_username), main_type), sub_type).replace(
"\\", "/")
if not os.path.exists(dir):
os.makedirs(dir)
destination = open(os.path.join(dir, File.name).replace("\\", "/"),
'wb+')
for chunk in File.chunks():
destination.write(chunk)
destination.close()
resp = vars(RespDatas(1, '200', ''))
return Response(resp)
二、文件下载
def post(self, request):
# 文件下载
if int(request.data.get("flag", None)) == 4:
mes = redis_resp.hgetall("staff")
mes_username = mes.get("username")
print("flag")
print(request.data.get("flag", None))
file = request.data.get("file")
main_type = request.data.get("main_type")
sub_type = request.data.get("sub_type")
the_file_path = os.path.join(
os.path.join(os.path.join(os.path.join(FILE_PATH, mes_username), main_type), sub_type), file).replace(
"\\", "/")
response = StreamingHttpResponse(file_iterator(the_file_path))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = "attachment; filename*=utf-8''{}".format(escape_uri_path(file))
# response['Content-Type'] = 'application/octet-stream'
# response['Content-Disposition'] = 'attachement;filename="{0}"'.format(file)
return response
三、文件夹打包下载(zip)
def post(self, request):
#压缩包下载
if int(request.data.get("flag", None)) == 5:
mes = redis_resp.hgetall("staff")
mes_username = mes.get("username")
the_file_path = os.path.join(os.path.join(os.path.join(FILE_PATH, mes_username))).replace("\\", "/")
print(the_file_path)
try:
#打包文件
zip_dir(FILE_PATH.replace("\\", "/"), "test.zip")
the_file_name=os.path.join(FILE_PATH,"test.zip").replace("\\", "/")
response = StreamingHttpResponse(file_iterator(the_file_name))
response['Content-Type'] = 'application/octet-stream'
response['Content-Disposition'] = 'attachment;filename="{0}"'.format(escape_uri_path(the_file_name))
return response
except:
resp = vars(RespDatas(1, '400', '下载失败'))
return Response(resp)
参考:https://blog.csdn.net/weixin_30302609/article/details/97728518
标签:
Django
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?