Django實現檔案上傳、下載
阿新 • • 發佈:2022-03-23
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