1. 程式人生 > 程式設計 >python基於FTP實現檔案傳輸相關功能程式碼例項

python基於FTP實現檔案傳輸相關功能程式碼例項

這篇文章主要介紹了python基於FTP實現檔案傳輸相關功能程式碼例項,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下

本例項有檔案傳輸相關功能,包括:檔案校驗、進度條列印、斷點續傳

客戶端示例:

import socket
import json
import os
import hashlib

CODE = {
  '1001':'重新上傳檔案'
}

def file_md5(file_path):
  obj = open(file_path,'rb')
  m = hashlib.md5()
  for line in obj:
    m.update(line)
  obj.close()
  return m.hexdigest()

def jdt(size,total_size):
  '''
  顯示進度條
  '''
  val = int(size/total_size * 100)
  print('\r%s%%|%s' %(val,'#'*val,),end='')

def send_file(exist_size,file_total_size):
  '''
  傳送檔案
  :param exist_size: 開始讀取位元組的位置
  :param file_total_size: 檔案大小
  :return:
  '''
  f = open(file_path,'rb')
  f.seek(exist_size)
  send_size = exist_size
  while send_size < file_total_size:
    data = f.read(1024)
    sk.sendall(data)
    send_size += len(data)
    jdt(send_size,file_total_size)
  f.close()
  print('上傳成功')

def upload(file_path):
  '''檔案上傳(含斷點)'''
  file_path = '111.jpg'
  file_md5_val = file_md5(file_path)
  file_name = os.path.basename(file_path)
  file_size = os.stat(file_path).st_size

  cmd_dict = {'cmd': 'upload','file_name': file_name,'size': file_size,'md5': file_md5_val}
  upload_cmd_bytes = json.dumps(cmd_dict).encode('utf8')
  sk.sendall(upload_cmd_bytes)

  # 2.等待服務端相應
  response = json.loads(sk.recv(8096).decode('utf8'))
  if response['code'] == 1001:
    send_file(0,file_size)
  else: # 斷點續傳
    exist_size = response('size')
    send_file(exist_size,file_size)

sk = socket.socket()
sk.connect(('127.0.0.1',8001))

while 1:
  #upload|檔案路徑
  user_input = input('命令>>>')
  # 1、自定義協議{'cmd':'upload','file_name':'...'}
  cmd,file_path = user_input.split('|',maxsplit=1)
  if cmd == 'upload':
    upload(file_path)
  elif cmd == 'download':
    pass

服務端示例:

import socketserver
import json
import os
import shutil

CODE = {
  '1001':'重新上傳檔案'
}

def upload(cmd_dict,conn,username):
  '''服務端完成上傳檔案(含斷點續傳)'''
  # 2.獲取檔案資訊
  file_md5 = cmd_dict['md5']
  file_name = cmd_dict['file_name']
  file_md5_path = os.path.join('home',username,file_md5)
  file_name_path = os.path.join('home',file_name)
  upload_file_size = cmd_dict['size']

  # 3.判斷檔案是否存在
  exist = os.path.exists(file_md5_path)
  if not exist: # 不續傳
    # 3.1.1通知可以開始上傳,已經準備好
    response = {'code': 1001}
    conn.sendall(json.dumps(response).encode('utf8'))

    # 3.1.2接收上傳的檔案內容
    f = open(file_md5_path,'wb')
    recv_size = 0
    while recv_size < upload_file_size:
      data = conn.recv(1024)
      f.write(data) # 寫到記憶體
      f.flush() # 刷到硬碟
      recv_size += len(data)
    f.close()

    # 3.1.3改檔名
    shutil.move(file_md5_path,file_name_path)

  else: # 存在就續傳
    # 3.2續傳 + 大小
    exist_size = os.stat(file_md5_path).st_size
    response = {'code': 1002,'size': exist_size}
    conn.sendall(json.dumps(response).encode('utf8'))

    f = open(file_md5_path,'ab')
    recv_size = exist_size
    while recv_size < upload_file_size:
      data = conn.recv(1024)
      f.write(data) # 寫到記憶體
      f.flush() # 刷到硬碟
      recv_size += len(data)
    f.close()

    # 3.1.3改檔名
    shutil.move(file_md5_path,file_name_path)


class NBServer(socketserver.BaseRequestHandler):
  def handle(self):
    '''self.request是請求客戶端的socket物件'''

    #1.接受命令
    upload_cmd_bytes = self.request.recv(8096)
    cmd_dict = json.loads(upload_cmd_bytes.decode('utf8'))

    if cmd_dict['cmd'] == 'upload':
      upload(cmd_dict,self.request,'zhangzijian')
    elif cmd_dict['cmd'] == 'download':
      pass

if __name__ == '__main__':
  server = socketserver.ThreadingTCPServer(('127.0.0.1',8001),NBServer)
  server.serve_forever()

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。