TOP

django 中对文件相关操作 (上传下载)

上传文件

随机文件夹创建

上传时如果考虑多用户同时上传同一份文件

极端一些可以考虑多用户同时使用一个账号同时对一个重名文件进行上传之类的

所以这里如果需要, 可以对每一次的上传文件的请求进行唯一标识比如用时间轴之类的区分开

    @staticmethod
    def tmp_dir(file_name, need_time_str=True):
        random_str = file_name + str(time.time()) if need_time_str else ""
        # 临时文件夹路径
        tmp_dir_path = os.path.join(os.path.join(settings.BASE_DIR, 'static'), random_str)
        os.mkdir(tmp_dir_path)
        return tmp_dir_path, os.path.join(tmp_dir_path, file_name)

.... 

    tmp_path, file_path = self.tmp_dir(file.name)  # 创建临时文件夹
    os.remove(file_path)  # 视情况看是否上传完毕后进行清除
    os.rmdir(tmp_path)  # 清除临时文件夹

获取上传文件

在视图函数中进行操作, request 中的 FILES 中可以取到 (固定关键字 file)

file = request.FILES["file"]

上传文件存储

结合上面创建的随机文件夹, 讲文件存储在随机文件夹下

        # 保存文件在本地静态文件夹随机文件夹下
        tmp_path, file_path = self.tmp_dir(file.name)  # 创建临时文件夹
        destination = open(os.path.join(tmp_path, file.name), 'wb+')
        for chunk in file.chunks():
            destination.write(chunk)  # 写入临时文件
        destination.close()

下载文件

        with open(file_path, "rb") as file_handle:
            p_response = FileResponse(file_handle.read())
            p_response["Content-Type"] = "application/octet-stream"
            p_response["Content-Disposition"] = f"attachment;filename={file_name}"
        return p_response    

下载文件格式较为固定, 直接对文件的路径进行 rb 形式读取后返回 FileResponse 即可

 

posted @ 2021-08-19 10:30  羊驼之歌  阅读(167)  评论(0编辑  收藏  举报