解压缩时,Python zip文件传输会引发错误

时间:2018-01-18 08:54:32

标签: python zip fileserver

我正在尝试将zip文件从客户端发送到服务器计算机。客户端正确压缩内容,但服务器无法接收内容并将其解压缩。

服务器代码:

import socket
import sys
import os
import zipfile

HOST = ""
PORT = 9999

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(5)
target = "C:\\first example\\Python_exapmles\\Recieved_files"
output = os.path.join(target, "result.zip")

print("Listening ...")
# output="result.zip"
foo = zipfile.ZipFile(output, 'w')
while True:
    conn, addr = s.accept()
    print("[+] Client connected: ", addr)
    # get file name to download
    foo = open(output, "wb")
    while True:
        # get file bytes
        data = conn.recv(4096)
        print(data)
        if not data:
            break
        # write bytes on file
        foo.write(data)

    zip = zipfile.ZipFile(r'C:\\first example\\Python_exapmles\\Recieved_files\\result.zip')
    zip.extractall(r'C:\\first example\\Python_exapmles\\after_extract')
    foo.close()
    print("[+] Download complete!")
    # close connection
    conn.close()
    print("[-] Client disconnected")

    sys.exit(0)

客户代码:

import socket
import sys
import sys
import os
import zipfile

host= '192.168.1.205'
port=9999

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))

print("[+] connected with server")

source="C:\\New folder\\zipfoldername"
target='C:\\New folder'
output=os.path.join(target, "01-lam-nat-conv.zip")
print (output)
foo = zipfile.ZipFile(output, 'w')

for root, dirs, files in os.walk(source):
    path=root.replace(source, "01-lam-nat-conv")
    #prist path
    for f in files:
        foo.write(os.path.join(root, f), path + "//" + f)  # zipfile.ZIP_STORED)



f_send=output
#open file

with open(f_send,"rb") as f:
    data=f.read()
    s.sendall(data)

    s.close()
    sys.exit(0)

运行客户端后的输出将退出"退出代码0"并且zip已正确完成但在服务器中我收到以下错误。

  

第1108行, init &第1175行,_RealGetContents zipfile.BadZipFile:文件不是zip文件

1 个答案:

答案 0 :(得分:0)

在服务器代码中,您将值分配给 ((inpList .Intersect(x.B.Select(b=>b.CodeID)) .ToList() .Count()==inpList.Count()) || (inpList.Count() == 0)) 变量两次
foofoo = zipfile.ZipFile(output, 'w')

执行后一行后

foo = open(output, "wb")不再是 Zipfile 删除后一行应该修复你的代码