如何在Python中从本地服务器下载文件 [英] How to download file from local server in Python
本文介绍了如何在Python中从本地服务器下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
场景是:
- 客户将输入文件名,例如 xyz
- 服务器将显示它在不同文件夹中的所有文件.
客户将选择 1 或 2 或 3(如果有).和文件将被下载.
Client will select 1 or 2 or 3 (if there). and file will be downloaded.
我已经完成了搜索部分.我需要有关下载文件并将其保存在任何其他目录中的帮助.
到目前为止,我的代码是用于搜索文件.
My code so far is for searching the file.
import socket
tcp_ip="127.0.0.1"
tcp_port=1024
buffer_size= 200
filename=raw_input("Enter file name\n")
s= socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((tcp_ip,tcp_port))
data=s.recv(buffer_size)
s.close()
服务器代码:(此代码现在用于一个文件)所需的帮助是如何下载和保存在服务器上找到的文件.
Server Code : (This code is now for one file) The required help is how to download and save that file which is found at server.
import socket
import os
tcp_ip='127.0.0.1'
tcp_port=1024
buffer_size=100
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((tcp_ip, tcp_port))
s.listen(1)
conn, addr = s.accept()
print 'Connection Address:',addr
while 1:
data=conn.recv(buffer_size)
if not data:
break
else:
print "received server side data:", data
conn.send(data)
conn.close()
推荐答案
以下示例展示了如何通过 tcp 从服务器下载文件.
Following is the example which shows how to download a file from a server over tcp.
客户代码:
import socket
import os
HOST = 'localhost'
PORT = 1024
downloadDir = "/tmp"
filename = raw_input('Enter your filename: ')
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(filename)
with open(os.path.join(downloadDir, filename), 'wb') as file_to_write:
while True:
data = socket1.recv(1024)
if not data:
break
file_to_write.write(data)
file_to_write.close()
socket1.close()
服务器代码:
import socket
HOST = 'localhost'
PORT = 1024
socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket.bind((HOST, PORT))
socket.listen(1)
while (1):
conn, addr = socket.accept()
reqFile = conn.recv(1024)
with open(reqFile, 'rb') as file_to_send:
for data in file_to_send:
conn.sendall(data)
conn.close()
socket.close()
注意:服务器代码不健壮,当文件不存在时会崩溃.您应该根据需要修改上面的示例.
Note: server code is not robust and will crash when file doesn't exists. You should modify above example according to your needs.
这篇关于如何在Python中从本地服务器下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文