Sending different files from Client to Server in Python
Question: 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.


Answer: You either need to use a library such as
[ftputil](https://pypi.python.org/pypi/ftputil/2.2.3) or encode the file in
some way such as such as
[UUENCODE](https://docs.python.org/2/library/uu.html).

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._

