title: How to upload a file to server with Tkinter filedialog
body: <p>I have a client that let user to browse a file and upload to a server. Currently I'm just using command terminal to operate the program. When user types in <code>fup</code> in the terminal, the program will ask for filename and the file will be uploaded to the server if the filename input by user is valid.</p>
  <p>So, what I want now is letting user to browse any file directory from a GUI without typing the filename to upload. I've tried to implement <code>filedialog</code> but it seems like not working. When I browse and upload a file, the server does not receive any new file. I am stuck with issues almost a week already but still couldn't find any solution. Hope someone could help me. Thanks in advance.</p>
  <p><strong>Client.py</strong></p>
  <pre><code>import socket, sys, os
  from tkinter import filedialog
  from tkinter import *
  
  import time, shutil
  root = Tk()
  # socket creating
  def sock():
      try:
          s = socket.socket()
          host = input('Enter Target IP :')
          port = 9999
          s.connect((host, port))
          return (host, s)
      except:
          print(&quot;Error: In binding&quot;)
          sock()
  
  
  host, s = sock()
  
  # upload file to client
  
  def fup(conn):
      try:
          filename = filedialog.askopenfilename(parent=root, initialdir=&quot;/&quot;, title='Please select a directory')
          if os.path.isfile(filename):
              conn.send(str(&quot;fup~&quot; + filename).encode(&quot;utf-8&quot;))
              conn.send(str.encode(&quot;EXISTS &quot; + str(os.path.getsize(filename))))
              filesize = int(os.path.getsize(filename))
              userResponse = conn.recv(1024).decode(&quot;utf-8&quot;)
              if userResponse[:2] == 'OK':
                  with open(filename, 'rb') as f:
                      bytesToSend = f.read(1024)
                      conn.send(bytesToSend)
                      totalSend = len(bytesToSend)
                      while int(totalSend) &lt; int(filesize):
                          bytesToSend = f.read(1024)
                          totalSend += len(bytesToSend)
                          conn.send(bytesToSend)
                          sys.stdout.write(&quot;\r|&quot; + &quot;█&quot; * int((totalSend / float(filesize)) * 50) + &quot;|{0:.2f}&quot;.format(
                              (totalSend / float(filesize)) * 100) + &quot;%  &quot;)
                          sys.stdout.flush()
                      print(&quot;\nUpload Completed!&quot;)
          else:
              print(&quot;File Does Not Exist!&quot;)
      except:
          print(&quot;Error&quot;)
  
  
  # download file from client
  def fdown(conn):
      try:
          print(os.getcwd())
          filename = input(&quot;\nMANO &gt;&gt;Filename? -&gt; &quot;)
          if filename != 'q':
              conn.send((&quot;fdown~&quot; + filename).encode(&quot;utf-8&quot;))
              data = conn.recv(1024).decode(&quot;utf-8&quot;)
              if data[:6] == 'EXISTS':
                  filesize = data[6:]
                  msg = input(&quot;File exists, &quot; + str(filesize) + &quot;Bytes, download? (Y/N)? -&gt; &quot;).upper()
                  if msg == 'Y':
                      conn.send(&quot;OK&quot;.encode(&quot;utf-8&quot;))
                      f = open(filename, 'wb')
                      data = (conn.recv(1024))
                      totalRecv = len(data)
                      f.write(data)
                      while int(totalRecv) &lt; int(filesize):
                          data = conn.recv(1024)
                          totalRecv += len(data)
                          f.write(data)
                          sys.stdout.write(&quot;\r|&quot; + &quot;█&quot; * int((totalRecv / float(filesize)) * 50) + &quot;|{0:.2f}&quot;.format(
                              (totalRecv / float(filesize)) * 100) + &quot;%  &quot;)
                          sys.stdout.flush()
                          time.sleep(0.01)
                      print(&quot;\nDownload Complete!&quot;)
                      f.close()
              else:
                  print(&quot;File Does Not Exist!&quot;)
      except:
          print(&quot;Error&quot;)
  
  
  # commands that perform on client
  def mano(cip, conn):
      fup(conn)
  
  
  def run():
      mano(host, s)
  
  upload_button = Button(root, text=&quot;upload&quot;, command=run)
  upload_button.place(x=130, y=17, width=50, height=22)
  
  root.mainloop()
  </code></pre>
  <p>Server.py</p>
  <pre><code>import socket, os, subprocess, shutil, pickle, struct, threading
  ## gettig the hostname by socket.gethostname() method
  hostname = socket.gethostname()
  ## getting the IP address using socket.gethostbyname() method
  ip_address = socket.gethostbyname(hostname)
  
  # Create a Socket ( connect two computers)
  
  def create_socket():
      try:
          global host
          global port
          global s
          host = &quot;&quot;
          port = 9999
          s = socket.socket()
      except socket.error as msg:
          create_socket()
  
  # Binding the socket and listening for connections
  def bind_socket():
      try:
          global host
          global port
          global s
          s.bind((host, port))
          s.listen(5)
          ## printing the hostname and ip_address
          print(f&quot;Hostname: {hostname}&quot;)
          print(f&quot;IP Address: {ip_address}&quot;)
          print(f&quot;Running Port: {port}&quot;)
      except socket.error as msg:
          bind_socket()
          print(bind_socket())
  
  
  # send file list
  def flist(conn):
      try:
          arr = pickle.dumps(os.listdir())
          conn.send(arr)
          print(arr)
      except:
          conn.send(('Error').encode(&quot;utf-8&quot;))
  
  
  # accept file from server
  
  def fdown(filename, conn):
      try:
          data = conn.recv(1024).decode(&quot;utf-8&quot;)
          if data[:6] == 'EXISTS':
              filesize = data[6:]
              conn.send(&quot;OK&quot;.encode(&quot;utf-8&quot;))
              f = open(filename, 'wb')
              data = (conn.recv(1024))
              totalRecv = len(data)
              f.write(data)
              while int(totalRecv) &lt; int(filesize):
                  data = conn.recv(1024)
                  totalRecv += len(data)
                  f.write(data)
              f.close()
      except:
          conn.send(('Error').encode(&quot;utf-8&quot;))
  
  
  # send file
  
  def fup(filename, conn):
      if os.path.isfile(filename):
          conn.send(str.encode(&quot;EXISTS &quot; + str(os.path.getsize(filename))))
          filesize = int(os.path.getsize(filename))
          userResponse = conn.recv(1024).decode(&quot;utf-8&quot;)
          if userResponse[:2] == 'OK':
              with open(filename, 'rb') as f:
                  bytesToSend = f.read(1024)
                  conn.send(bytesToSend)
                  totalSend = len(bytesToSend)
                  while int(totalSend) &lt; int(filesize):
                      bytesToSend = f.read(1024)
                      totalSend += len(bytesToSend)
                      conn.send(bytesToSend)
      else:
          conn.send(&quot;ERROR&quot;.encode(&quot;utf-8&quot;))
  
  
  # main
  def main(s):
      while True:
          data = (s.recv(1024)).decode(&quot;utf-8&quot;).split('~')
          if data[0] == 'fdown':
              fup(data[1], s)
          elif data[0] == 'fup':
              fdown(data[1], s)
          elif data[0] == 'flist':
              flist(s)
          else:
              s.send(&quot;.&quot;.encode('utf-8'))
  
  
  def socket_accept():
      while True:
          conn, address = s.accept()
          t = threading.Thread(target=main, args=(conn,))
          t.start()
  
  
  create_socket()
  bind_socket()
  socket_accept()
  </code></pre>
  <p>**After I click on upload and it show uploaded compelte, but the server doesn't receive any new file.
  <a href="https://i.stack.imgur.com/uL1K1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uL1K1.png" alt="enter image description here" /></a></p>