1. 上传脚本的python代码
def upload():
# buld post body data
boundary = '----------%s' % hex(int(time.time() * 1000))
# 换成自己的url
http_url = 'https://XXXXX/upload_api'
data = []
data.append('--%s' % boundary)
data.append('Content-Disposition: form-data; name="%s"; filename="%s"' % ('file', 'data.txt'))
data.append('Content-Type: %s\r\n' % 'text/html')
fr = open(r'/tmp/data.txt', 'rb')
data.append(fr.read())
fr.close()
data.append('--%s--\r\n' % boundary)
http_body = '\r\n'.join(data)
try:
req = urllib2.Request(http_url, data=http_body)
req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary)
req.add_header('User-Agent', 'Mozilla/5.0')
# 换成自己的 Authorization,如果没有的话,可以不写
req.add_header('Authorization', 'XXXXXX')
res = urllib2.urlopen(req, context=ssl.SSLContext(ssl.PROTOCOL_TLSv1), timeout=5)
# print ('res---------',res.read().decode('utf8'))
except Exception as e:
print ('Error: %s' % e)
upload()
以上py执行的时候,已经模拟网页前端发送了上传请求。
2. 服务端接收上传文件并保存
def action_upload_target():
if request.method != "POST":
return
if not request.content_type.startswith("multipart/form-data"):
return
target = ''
if 'file' in request.files:
file_metas = request.files['file']
for meta in file_metas:
target += meta.decode()
return target
def upload_api():
#校验Authorization
status, info = check_auth()
if not status:
return info
#权限通过后,逐行解析上传的文件
target = action_upload_target()
#把文件内容写入到本地保存
file_object = open('/tmp/test_upload.txt', 'w')
file_object.write(target)
file_object.close()
return "success"