美文网首页
tornado 文件上传

tornado 文件上传

作者: 时尚灬IT男 | 来源:发表于2022-03-14 15:34 被阅读0次

    主体部分

    class uploadReport(BaseHandler):
        def options(self):
            pass
        @gen.coroutine
        def post(self):
            try:
                auth_header = self.request.headers.get('Authorization', None)
                if auth_header is not None:
                    userID = base_token_valid(auth_header)
                    if userID:
                        #result = self.request.body.decode('utf-8')
                        projectID = self.get_body_arguments("projectID")[0]
                        reportType = self.get_body_arguments("reportType")[0]
                        file_metas = self.request.files.get('file', None)  # 提取表单中‘name'为‘file'的文件元数据
                        result = yield model.uploadReport(file_metas,projectID,reportType,userID)
                        # print(result)
    
                        self.write(json.dumps(result, cls=JsonToDatetime, ensure_ascii=False))
                    else:
                        self.write('authentication fail')
                else:
                    self.write('authentication fail')
    
            except Exception as e:
                self.write(json.dumps({"data":"authentication fail","message":"{}".format(e)}, ensure_ascii=False))
    

    方法实现部分

    
    @gen.coroutine
    def uploadReport(file_metas,projectID,reportType,userID):
        try:
            ret = {'result': 'OK'}
            
            upload_path = os.path.join(os.path.dirname(__file__), 'files/{}/{}'.format(projectID,reportType))  # 文件的暂存路径,按项目,类型层级
    
            if not file_metas:
                ret['result'] = 'Invalid Args'
                return ret
            for meta in file_metas:
                filename = meta['filename']
                file_path = os.path.join(upload_path, filename)
    
                if not os.path.exists(os.path.split(file_path)[0]):
                    # 目录不存在创建,makedirs可以创建多级目录
                    os.makedirs(os.path.split(file_path)[0])
    
                with open(file_path, 'wb') as up:
                    up.write(meta['body'])
    
        except Exception as e:
            ret = {'result': str(e)}
        raise gen.Return(ret)
    

    客户端请求访问

    image.png

    相关文章

      网友评论

          本文标题:tornado 文件上传

          本文链接:https://www.haomeiwen.com/subject/jutsdrtx.html