向Web服务器端上传文件
server.py
import flask
app = flask.Flask(__name__)
@app.route('/upload', methods=['POST'])
def uploadFile():
msg = ""
try:
if "fileName" in flask.request.values:
fileName = flask.request.values.get("fileName")
data = flask.request.get_data("data")
fobj = open("upload" + fileName, 'wb')
fobj.write(data)
fobj.close()
msg = "OK"
else:
msg = "请按要求上传文件"
except Exception as e:
print(e)
msg = str(e)
return msg
if __name__ == '__main__':
app.run()
client.py
import urllib.request import urllib.parse url = "http://127.0.0.1:5000" fileName = "testimg.jpg" try: fobj = open("testimg.jpg", "rb") data = fobj.read() fobj.close() headers = {"Content-Type": "application/octet-stream"} url = url + "?fileName=" + urllib.parse.quote(fileName) request = urllib.request.Request(url, data, headers) response = urllib.request.urlopen(request) msg = response.read().decode() print(msg) except Exception as e: print(e)