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

posted @   Jaetyn  阅读(1692)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
点击右上角即可分享
微信分享提示