zoukankan      html  css  js  c++  java
  • django 实现zip包下载

    class TaskCenterDownload(APIView):
    
        def get(self,request):
    
            file_path = str(BASE_DIR) + 'download_file\main.zip'
            file_name = 'main'
          
            if not os.path.isfile(file_path):
                return HttpResponeseJson(code=400,message="Sorry but Not Found the File")
    
            def file_iterator(file_path, chunk_size=512):
                """
                文件生成器,防止文件过大,导致内存溢出
                :param file_path: 文件绝对路径
                :param chunk_size: 块大小
                :return: 生成器
                """
                with open(file_path, mode='rb') as f:
                    while True:
                        c = f.read(chunk_size)
                        if c:
                            yield c
                        else:
                            break
    
            try:
                # 设置响应头
                # StreamingHttpResponse将文件内容进行流式传输,数据量大可以用这个方法(.pdf,.zip,.mp4等等什么样格式的文件都可以下载)
                response = StreamingHttpResponse(file_iterator(file_path))
                # 以流的形式下载文件,这样可以实现任意格式的文件下载
                response['Content-Type'] = 'application/octet-stream'
                # Content-Disposition就是当用户想把请求所得的内容存为一个文件的时候提供一个默认的文件名
                response['Content-Disposition'] = 'attachment;filename={file_name}{format}'.format(
                    file_name=file_name, format=".zip")
            except:
                return HttpResponeseJson(code=400,message="Sorry but Not Found the File")
    
                # 在这里千万记得return,否则不会出现下载
            return response
    
    def HttpResponeseJson(data=None, code='200', message='success'):
        try:
            rep = {
                "code": str(code),
    
                "message": message,
                "data": data
            }
            return Response(rep)
        except Exception as e:
            logger.error(f'序列化json出错{e}')
            return Response({'message': '序列化json出错'})
    
  • 相关阅读:
    P2149 [SDOI2009]Elaxia的路线
    P1346 电车
    P3174 [HAOI2009]毛毛虫
    P3047 [USACO12FEB]附近的牛Nearby Cows
    P4053 [JSOI2007]建筑抢修
    P2607 [ZJOI2008]骑士
    [HNOI2006]马步距离
    [POI2014]Hotel
    [BZOJ3856]Monster
    [BZOJ2819]Nim
  • 原文地址:https://www.cnblogs.com/qxh-beijing2016/p/13890003.html
Copyright © 2011-2022 走看看