[英]Sending different files from Client to Server in Python
我正在嘗試使用python將文件從客戶端發送到服務器。 它正在發送,但是問題是我沒有得到相同的文件名。 假設文件名是File1.txt。 將其發送到服務器時,將以file_.txt的形式接收 。 我為此編寫的代碼是:
客戶代碼
import socket, os, shutil
from stat import ST_SIZE
HOST=raw_input("Please enter IP-address : ")
PORT=int(raw_input("Please enter PORT Number : "))
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))
if s.recv(8)!='READY':
raw_input('Unable to connect \n\n Press any key to exit ...')
s.close()
exit()
path=raw_input("Please enter the complete PATH of your file : ")
f=open(path,'rb')
fsize=os.stat(f.name)[ST_SIZE]
s.sendall(str(fsize).zfill(8))
sfile = s.makefile("wb")
shutil.copyfileobj(f, sfile)
sfile.close()
s.close()
f.close()
服務器代碼
import socket
import shutil
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = ''
PORT = 31400
s.bind((HOST, PORT))
s.listen(3)
conn, addr = s.accept()
print 'conn at address',addr
conn.sendall('READY')
i=1
f = open(r'file_'+ str(i)+".txt",'wb')
i=i+1
fsize=int(conn.recv(8))
print 'File size',fsize
sfile = conn.makefile("rb")
shutil.copyfileobj(sfile, f)
sfile.close()
f.write(conn.recv(fsize))
f.close()
conn.close()
s.close()
如何獲得相同的文件名...以及如果我必須接收任何類型的文件(如.pdf,.txt,.jpeg等)怎么辦。請幫助我,我是python的新手。
您要么需要使用ftputil之類的庫, 要么以某種方式對文件進行編碼,例如UUENCODE 。
或者,您將必須使用單獨的事務來實現自己的協議,以發送文件名和大小,然后發送內容。 即
請注意,以上內容並未涵蓋處理問題,例如數據丟失,僅ASCII鏈接,損壞,作為塊發送等。請記住,FTP自1971年以來一直在積極使用和開發,並建議在1998年后期進行根本性的更改。
首先,您沒有在服務器端以file_.txt的形式收到它,而是打開一個名為file_.txt的新文件,並將其從服務器端收到的內容復制到新創建的file_中。文本
我的解決方案是從文件中獲取文件名,並將其與內容一起發送。 獲取文件名示例:
import os
print os.path.splitext("path_to_file")[0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.