Django实现文件上传下载

Posted Jaetyn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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实现文件上传下载的主要内容,如果未能解决你的问题,请参考以下文章

Django 如何实现文件下载

django实现文件上传到服务器

django实现分片上传文件

django实现快速文件上传

Django实现文件的上传

django 实现文件上传