zoukankan      html  css  js  c++  java
  • 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 即可

    本文来自博客园,作者:羊驼之歌,转载请注明原文链接:https://www.cnblogs.com/shijieli/p/15160551.html

  • 相关阅读:
    从Android源码修改cpu信息
    lintcode-->翻转字符串
    lintcode-->哈希函数
    PCP架构设计
    PCP项目立项
    linux下wc功能的简单实现
    goahead3.6.3就基本使用(后台上传信息到html页面),高手请忽略
    四则运算生成器
    快速看完软件工程教材后,我的疑惑
    软件工程学习
  • 原文地址:https://www.cnblogs.com/shijieli/p/15160551.html
Copyright © 2011-2022 走看看