tornado 文件上传

场景:前端会先计算出文件md5值一并传送给后端

         后端需要判断文件对应md5是否存在

         支持多文件上传

服务端

import os

import hashlib

#上传文件
def fileAdd(self):
    my_dir = os.path.join(os.path.dirname(__file__), '..', 'log', 'vulnerability_database')
    if os.path.isdir(my_dir) is False:
        os.makedirs(my_dir)

    file_data = self.request.files
    md5_dic=self.request.arguments

    #判断所有文件必须有md5,md5必须为真
    for m in file_data.keys():
        if m not in md5_dic or len(md5_dic[m][0])==0 or len(md5_dic[m][0].decode().strip())==0:
            msg_ret = self.get_response('error', '文件md5必须为真', [])
            self.write(msg_ret)
            return



    if file_data:
        sql_list=[]
        for fk,fv in file_data.items():
#fk:file2 fv:[{'filename': '2.txt', 'body': b'bbb ', 'content_type': 'application/unknown'}] file_md5
=md5_dic[fk][0].decode().strip() file_name=fv[0]['filename'] file_body=fv[0]['body'] file_body_len=len(fv[0]['body']) try: my_file = os.path.join(os.path.dirname(__file__), my_dir, file_name) #计算md5 # myHash = hashlib.md5() with open(my_file, 'wb') as f: f.write(file_body) # myHash.update(file_body) # my_md5=myHash.hexdigest()
# 没有异常就算成功 except Exception as e: msg_ret = self.get_response('error', '%s 写入失败' % (file_name), []) self.write(msg_ret) return else: msg_ret = self.get_response('error', '没有选中上传文件', []) self.write(msg_ret)

  

客户端

url = "http://127.0.0.1:7101/file/fileAdd"

#前端计算文件md5值 payload
= {"file1":"xxx","file2":"xxx"} files = [ ('file1', open('/Users/xxx/Desktop/logo/1.txt','rb')), ('file2', open('/Users/xxx/Desktop/logo/2.txt','rb')) ] headers= {} response = requests.request("POST", url, headers=headers, data = payload, files = files) print(response.text)

  

原文地址:https://www.cnblogs.com/zhangkui/p/11533895.html