从服务器发送文件到客户端(python)

时间:2013-05-28 11:19:21

标签: python client-server file-transfer

我目前正在编写一个需要传输某些文件才能工作的服务器 - 客户端应用程序。 我正在使用这种方法:

客户端:

file_to_send = raw_input(">") 

try:
    f = open("./sent_files/" + file_to_send, "rb")
except IOError, e:
    print ">error: ", e
    break

data = xmlrpclib.Binary(f.read())

if s.receive_file(file_to_send, data):
    print ">file correctly sent"

服务器

def receive_file(self, name, arg):                                        
    with open("./sampletest/"+name, "wb") as handle: 
        handle.write(arg.data)

但我怎么能做相反的事情(我的意思是从服务器向客户端发送文件)?

1 个答案:

答案 0 :(得分:5)

只需在服务器上编写一个函数,如下所示:

def send_file(self, name):
  with open('./sampletest/' + name, 'rb') as handle:
    return handle.read()

并在客户端上调用它:

data = send_file(fileName)
with open('./received_files/' + fileName, 'wb') as handle:
  handle.write(data)