python3中flask上傳檔案:影象.jpg
阿新 • • 發佈:2018-12-18
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)