Django实现文件上传及下载的方式,FileSystemStorage和StreamingHttpResponse的使用

文件保存的路径配置

python 复制代码
import platform

system = platform.system()  # 获取当前系统类型
if system == "Windows":  # 测试环境
    MEDIA_ROOT = "F:/Download/media/"
    DOMAIN = "http://127.0.0.1/"
elif system == "Linux":  # 线上环境
    MEDIA_ROOT = "/mnt/media/"
    DOMAIN = "http://xxxx.com/"
else:
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
    DOMAIN = "http://127.0.0.1/"

# print(MEDIA_ROOT)

MEDIA_URL = '/media/'

一、文件上传

1,使用自带的FileSystemStorage类

简单功能实现

python 复制代码
from django.views import View
from django.core.files.storage import FileSystemStorage


class SingleMediaView(View):
    def post(self, request):
        file = request.FILES.get('file', None)
        # 保存上传的文件到指定的绝对目录
        fs = FileSystemStorage()
        real_path = settings.MEDIA_ROOT + format_filename
        fs.save(real_path, file)
        return JsonResponse({"status": 200, "msg": "上传成功"})
2,使用open函数
python 复制代码
from django.views import View


class SingleMediaView(View):
    def post(self, request):
        file = request.FILES.get('file', 'None')
       
        with open('path/file.txt', 'wb+') as destination:
            for chunk in file.chunks():
                destination.write(chunk)
        return JsonResponse({"status": 200, "msg": "上传成功"})

open函数的第一方法写具体保存文件的路径

二、下载文件

使用StreamingHttpResponse类

python 复制代码
class DownloadFileView(View):
    """文件下载"""
    def get(self, request):
        file_id = request.GET.get("file_id", None)  # 文件id

        if file_id:
            media = Media.objects.get(id=file_id)  # 查询数据库
            real_path = settings.MEDIA_ROOT + media.url  # 获取文件路径

            # 使用StreamingHttpResponse进行大文件下载,不占内存
            def file_iterator(file_path, chunk_size=8192):
                with open(file_path, 'rb') as file:
                    while True:
                        data = file.read(chunk_size)
                        if not data:
                            break
                        yield data

            file_format = media.format
            response = StreamingHttpResponse(file_iterator(real_path))
            if media.type == 1:  # 图片下载
                response['Content-Type'] = f'image/{file_format}'
            elif media.type == 2:  # 视频下载
                response['Content-Type'] = f'video/{file_format}'
            elif media.type == 3:  # 其他类型文件下载
                response['Content-Type'] = 'application/octet-stream'

            # 使用quote对下载的中文文件名进行url编码,否则在Content-Disposition里的filename无法正确识别
            encoded_string = quote(f'{media.title}.{file_format.lower()}')
            response['Content-Disposition'] = f'attachment; filename="{encoded_string}"'

            return response

为DownloadFileView类视图配置url后请求时就可以直接下载了

相关推荐
小葱炖豆腐1 小时前
python绘制excel折线图
python·excel·numpy·pandas·matplotlib
IT_陈寒1 小时前
Java Stream处理大集合,我的内存怎么就炸了
前端·人工智能·后端
Ticnix2 小时前
MCP 实战:把工具层从 Agent 里彻底解耦
python·mcp
悟空码字2 小时前
四轮对话两张配图:用 WorkBuddy 优化公众号发文配图的实战指南
人工智能·后端·腾讯
ServBay2 小时前
xAI的 Grok Bot发布,AI 已经学会自己上班了
后端·ai编程·grok
分支预测失败2 小时前
RISC-V 多核缓存一致性机制解析:MESI 协议族、CMO 扩展与 Linux 同步原语
后端
n8n2 小时前
Spring AI 检索增强生成(RAG)实战:让模型掌握你的私有知识
后端
Nturmoils2 小时前
只备份一个 schema,别把整库都搬走
后端
妙码生花2 小时前
利用AI从零学Go并完成实战项目,完工总结:目录结构
前端·后端·go
妙码生花2 小时前
利用AI从零学Go并完成实战项目,完工总结:商业级开源产品定位和核心特性介绍
前端·后端·go