python3中flask下载文件:图像.jpg

downloaserver.py:

#!/usr/bin/env python

# coding=utf-8

# 服务器端,下载图像.jpg

import flask

import os

app = flask.Flask(__name__)

@app.route("/",methods=["GET","POST"])

def index():

# print(flask.request.values)

if "fileName" not in flask.request.values:

return "图像.jpg"

else:

data = b""

try:

fileName = flask.request.values.get("fileName")

if fileName != "" and os.path.exists(fileName):

with open(fileName,'rb')as f:

data = f.read()

except Exception as e:

data = str(e).encode()

return data

if __name__ == "__main__":

app.run()

downloadclient.py:

#!/usr/bin/env python

# coding=utf-8

# 客户端下载

import urllib.parse

import urllib.request

import time

url = "http://127.0.0.1:5000"

try:

request = urllib.request.urlopen(url)

response = request.read()

fileName = response.decode()

# GET方法下载

# data = urllib.request.urlopen(url+"?filename="+urllib.parse.quote(fileName))

# POS方法下载

filedata= "filename="+urllib.parse.quote(fileName)

data = urllib.request.urlopen(url,data=filedata.encode())

data = data.read()

print("准备下载文件%s,大小为%s字节:"%(fileName,len(data)))

time.sleep(3)

with open("download"+fileName,'wb')as f:

f.write(data)

print("下载完成,下载的文件大小%s字节"%len(data))

# 另一种下载图像方法,简便实用

# print("准备下载文件"+fileName)

# time.sleep(3)

# urllib.request.urlretrieve(url+"?filename="+urllib.parse.quote(fileName),"download"+fileName)

# print("下载完成!")

except Exception as e:

print(e)

python3中flask下载文件:图像.jpg

相关推荐