简体   繁体   English

如何在Python中从本地服务器下载文件

[英]How to download file from local server in Python

Scenario is: 场景是:

  1. Client will Enter a file name eg xyz 客户端将输入文件名,例如xyz
  2. Server will show all the files that it have in different folders. 服务器将显示它在不同文件夹中的所有文件。

Client will select 1 or 2 or 3 (if there). 客户将选择1或2或3(如果有)。 and file will be downloaded. 和文件将被下载。

I have done searching part. 我已经完成了搜索部分。 I want help in downloading and saving the file in any other directory. 我需要帮助来下载文件并将其保存在任何其他目录中。

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()

Following is the example which shows how to download a file from a server over tcp. 以下是显示如何通过tcp从服务器下载文件的示例。

Client Code: 客户代码:

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()

Server Code: 服务器代码:

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. 您应根据需要修改上述示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM