django 文件上传下载

该代码实现了一个API视图,用于读取和下载不同类型的文件(如jpg、png、mp4、avi)。通过静态方法处理GET请求时,根据文件类型返回对应的HTTP响应,包含图片或视频数据。POST请求则接收上传的文件,并保存到指定路径,返回文件的访问URL。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

class FileStoreView(APIView):

    @staticmethod
    def read_file(url, chunk_size=512):
        with open(url, "rb") as f:
            while True:
                c = f.read(chunk_size)
                if c:
                    yield c
                else:
                    break

    def get(self, request, *args, **kwargs):
        dir_path = os.getcwd() + '/oos_file/{}'.format(self.request.query_params.get('dir_path'))
        if dir_path.split("/")[-1].split(".")[-1] in ['jpg', 'png']:
            with open(dir_path, 'rb') as f:
                image_data = f.read()
            return HttpResponse(image_data, content_type="image/png")
        elif dir_path.split("/")[-1].split(".")[-1] == "mp4":
            with open(dir_path, 'rb') as f:
                image_data = f.read()
            return HttpResponse(image_data, content_type="video/mp4")
        elif dir_path.split("/")[-1].split(".")[-1] == "avi":
            with open(dir_path, 'rb') as f:
                image_data = f.read()
            return HttpResponse(image_data, content_type="video/avi")
        response = StreamingHttpResponse(self.read_file(dir_path))
        response["Content-Type"] = "application/octet-stream"
        response["Content-Disposition"] = 'attachment; filename={0}'.format(dir_path.split("/")[-1])
        response["Access-Control-Expose-Headers"] = "Content-Disposition"
        return response

    @staticmethod
    def post(request, *args, **kwargs):
        file = request.FILES.get('file')
        if not file:
            raise exceptions.ParseError("空文件?")
        uuid_str = int(time.time())
        dir_path = os.getcwd() + '/oos_file/{0}.{1}'.format(uuid_str, file.name.split(".")[-1])
        with open(dir_path, 'wb+') as f:
            for line in file.chunks():
                f.write(line)
        return Response("/api/user/file_suffix/{0}.{1}".format(uuid_str, file.name.split(".")[-1]))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值