python3中flask上传文件:图像.jpg
程序员文章站
2022-06-17 11:32:10
...
upload_server.py:
#!/usr/bin/env python
# coding=utf-8
# 文件上传服务器端,只考虑文件在当前目录下
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()
# 获取上传的文件名字:图像.jpg
# file = fileName[fileName.rfind("\\")+1:]
# 获取上传文件的路径D:\PycharmDevelop
# path = fileName[:fileName.rfind("\\")]
# with open(path +"\\"+"upload"+file,"wb")as f:
# f.write(data)
with open("upload"+fileName,"wb")as f:
f.write(data)
msg = "OK"
else:
msg = "没有按要求上传文件"
except Exception as e:
print(e)
msg = str(e)
return msg
if __name__ == "__main__":
app.run()
upload _client.py:
#!/usr/bin/env python
# coding=utf-8
# 文件上传客户端
import urllib.request
import urllib.parse
import os,time
url = "http://127.0.0.1:5000/upload"
fileName = input("请输入要上传的文件名字:")
try:
if os.path.exists(fileName):
with open(fileName,"rb")as f:
data = f.read()
print("准备上传文件:"+fileName)
time.sleep(3)
headers = {'content-type':'application/octet-stream'}
purl = url + "?fileName="+urllib.parse.quote(fileName)
req = urllib.request.Request(purl,data,headers)
response = urllib.request.urlopen(req)
msg = response.read().decode()
print(msg)
if msg == "OK":
print("成功上传文件:%s,大小为%s字节。"%(fileName,len(data)))
else:
print(msg)
else:
print("文件不存在!")
except Exception as e:
print(e)