django上传下载文件、下载压缩文件

  • 下载
import os
import base64
import pymysql
from rest_framework.views import APIView
from utils.core import APIResponse
from utils.core import get_user
from web_bubble import settings
from web_bubble.settings import DATABASES
from web_bubble.settings import BASE_DIR
from django.utils.http import urlquote
from django.http import StreamingHttpResponse
from utils.action_log import ActionLog


def get(self, request):
    with open(db_backup_name, "rt", encoding="utf-8")as f:
                base_read = f.read()
    response = StreamingHttpResponse(base_read, content_type='application/octet-stream')
    response['Content-Disposition'] = 'attachment;filename="%s"' % urlquote("db.sql")
          
    return response
    
  • 上传
def post(self, request, *args, **kwargs):
    sql_file = request.FILES.get("sql_file")
    if sql_file:
        sql_file = sql_file.read()
    with open(db_backup_name, "wt", encoding="utf-8")as f:
                    f.write(sql_file)
                return APIResponse(1, "success")
  • 下载压缩包
import zipstream

# 压缩文件逻辑
class ZipUtilities:
    zip_file = None

    def __init__(self):
        self.zip_file = zipstream.ZipFile(mode='w', compression=zipstream.ZIP_DEFLATED)

    def to_zip(self, file, name):
        if os.path.isfile(file):
            self.zip_file.write(file, arcname=os.path.basename(file))
        else:
            self.add_folder_to_zip(file, name)

    def add_folder_to_zip(self, folder, name):
        for file in os.listdir(folder):
            full_path = os.path.join(folder, file)
            if os.path.isfile(full_path):
                self.zip_file.write(full_path, arcname=os.path.join(name, os.path.basename(full_path)))
            elif os.path.isdir(full_path):
                self.add_folder_to_zip(full_path, os.path.join(name, os.path.basename(full_path)))

    def close(self):
        if self.zip_file:
            self.zip_file.close()
            
            
# 下载逻辑

def get(self, request, *args, **kwargs):
    certificate_path = "/text.txt"
    filename = "text"
    utilities.toZip(certificate_path, filename)
    response = StreamingHttpResponse(utilities.zip_file, content_type='application/zip')
    response['Content-Disposition'] = 'attachment;filename="%s"' % urlquote("证书.zip")
    return response
posted @ 2020-08-06 11:44  tianzhh_lynn  阅读(523)  评论(0编辑  收藏  举报