向web伺服器下載檔案

JJJhr發表於2024-05-19

web伺服器向客戶端傳送檔案

Web伺服器讀取一個檔案的二進位制資料,把這組二進位制資料傳送個客戶端,伺服器傳送給客戶端的HTML文件的本質也是二進位制。客戶端使用以下程式碼讀檔案

response = urllib.request.urlopen(url + "?" + urllib.parse.quote(fileName))
data = response.read()

server.py

import flask
app = flask.Flask(__name__)

@app.route('/', methods=['GET','POST'])
def index():
    if not "fileName" in flask.request.values:
        s = "test.jpg"
        return s
    else:
        fileName = flask.request.values.get("fileName")
        f = open(fileName, "rb")
        data = f.read()
        f.close()
        return data

if __name__ == '__main__':
    app.run()

clent.py

import urllib.request
import urllib.parse

url = "http://127.0.0.1:5000"
response = urllib.request.urlopen(url)
data = response.read()
fileName = data.decode('utf-8')
response = urllib.request.urlopen(url + "?" + urllib.parse.quote(fileName))
data = response.read()
f = open("dowmload" + fileName, "wb")
f.write(data)
f.close()
print(fileName, len(data))

靜態資料夾檔案下載

server.py

import flask
app = flask.Flask(__name__)

@app.route('/', methods=['GET','POST'])
def index():
    return "Image"

if __name__ == '__main__':
    app.run()

client.py

import urllib.request
import urllib.parse

url = "http://127.0.0.1:5000/static/test.jpg"
response = urllib.request.urlopen(url)
data = response.read()
f = open("dowmload test.jpg", "wb")
f.write(data)
f.close()
print("downloaded", len(data), "bytes")

相關文章