سؤال

I am trying to send files from client to server in python. It is sending but the problem is that I'm not getting same file name as it is. Suppose filename is File1.txt. When I send it to server, I receive it as file_.txt. The code I've wrote for this is :

Client Code

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

Server Code

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

How to get same file name...and what if I've to receive any type of file like .pdf, .txt, .jpeg etc. Please help me I'm new in python.

هل كانت مفيدة؟

المحلول

First of all you didn't receive it as file_.txt on the server side, you open a new file named it as file_.txt and copy the content from what you have received, on the server side, to the new created file_.txt

My solution were to get the filename from the file and send it with the content, too. Get file name example:

import os
print os.path.splitext("path_to_file")[0]

نصائح أخرى

You either need to use a library such as ftputil or encode the file in some way such as such as UUENCODE.

Alternatively you will have to implement your own protocol with separate transactions to send the file name and size then the contents. i.e.

  • Client gets the file path then checks the size plus splits off the basename.
  • Client sends the file base name and size in a pre-formatted manner.
  • Server receives and interprets the above information then opens the file called base name for write.
  • Client sends the binary data.
  • Server writes binary data to open file.
  • Both compute the MD5, or similar, for the file and exchange information to make sure it matches.

Note that the above does not cover handling problems such as lost data, ASCII only links, corruption, sending as blocks, etc. Bear in mind that FTP has been in active use and development since 1971 with fundamental change suggested as late as 1998.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top