要使用Python通過HTTP實(shí)現(xiàn)文件傳輸,可以使用Python的 requests 庫來發(fā)送和接收HTTP請(qǐng)求。以下是一個(gè)示例代碼,其中包括發(fā)送端和接收端的實(shí)現(xiàn)。
發(fā)送端:
import requests
def send_file(file_path, url):
with open(file_path, 'rb') as file:
response = requests.post(url, files={'file': file})
if response.status_code == 200:
print('File sent successfully.')
else:
print('Failed to send file.')
# 示例用法
file_path = 'path/to/file.txt'
url = 'http://example.com/receive-file'
send_file(file_path, url)
接收端:
from flask import Flask, request
app = Flask(__name__)
@app.route('/receive-file', methods=['POST'])
def receive_file():
file = request.files['file']
file.save('received_file.txt')
return 'File received successfully.'
if __name__ == '__main__':
app.run()
在這個(gè)示例中,發(fā)送端使用 requests.post() 方法發(fā)送文件到指定的URL。接收端使用Flask框架創(chuàng)建一個(gè)HTTP服務(wù)器,并在 /receive-file 路由上接收POST請(qǐng)求。接收端將接收到的文件保存為 received_file.txt 。
請(qǐng)注意,接收端腳本需要安裝Flask庫??梢允褂靡韵旅畎惭b它:文章來源:http://www.zghlxwxcb.cn/news/detail-617323.html
pip install flask
這只是一個(gè)基本示例,在實(shí)際應(yīng)用中,可能需要添加身份驗(yàn)證、安全性措施和錯(cuò)誤處理等功能。文章來源地址http://www.zghlxwxcb.cn/news/detail-617323.html
到了這里,關(guān)于用python通過http實(shí)現(xiàn)文件傳輸,分為發(fā)送端和接收端的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!