“社区您好,
我目前正在开发客户端-服务器应用程序,在将文件上传到服务器时遇到问题。似乎当我上传文件时,它没有以其原始名称、扩展名或内容保存。例如,如果我上传一个名为“file.txt”的包含特定信息的文件,它会简单地以“upload”形式保存在服务器上,而不保留其原始名称、扩展名或内容。
有人可以建议我如何确保上传到服务器的文件以其原始名称、扩展名和内容完整保存吗?任何有关解决此问题的帮助将不胜感激。
谢谢你!”
客户
import socket
import os
HOST = 'localhost'
PORT = 5173
def subir_archivo(socket_cliente, nombre_archivo):
socket_cliente.sendall(b"subir")
socket_cliente.sendall(nombre_archivo.encode('utf-8'))
with open(nombre_archivo, 'rb') as archivo:
contenido = archivo.read()
socket_cliente.sendall(contenido)
print("Archivo enviado al servidor:", nombre_archivo)
def descargar_archivo(socket_cliente, nombre_archivo):
socket_cliente.sendall(b"descargar")
socket_cliente.sendall(nombre_archivo.encode('utf-8'))
respuesta = socket_cliente.recv(1024)
if respuesta == b"EXISTE":
contenido = socket_cliente.recv(1024)
with open(nombre_archivo, 'wb') as archivo:
archivo.write(contenido)
print("Archivo descargado:", nombre_archivo)
else:
print("El archivo no existe en el servidor.")
opcion = input("¿Qué acción deseas realizar? (subir/descargar): ").lower()
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as cliente:
cliente.connect((HOST, PORT))
if opcion == 'subir':
nombre_archivo = input("Ingrese el nombre del archivo que desea subir: ")
subir_archivo(cliente, nombre_archivo)
if opcion == 'descargar':
nombre_archivo = input("Ingrese el nombre del archivo que desea descargar: ")
descargar_archivo(cliente, nombre_archivo)
服务器
import socket
import hashlib
import threading
HOST = "localhost"
PORT = 5173
def receive_file(client_socket):
# Receive the file name from the client
file_name = client_socket.recv(1024).decode()
# Receive the file content from the client
file_content = client_socket.recv(1024)
# Receive the hash of the file from the client
received_hash = client_socket.recv(1024).decode()
# Calculate the hash of the received file content
calculated_hash = hashlib.sha256(file_content).hexdigest()
# Write the received file content to a file
with open(file_name, 'wb') as file:
# Check if the calculated hash matches the received hash
if calculated_hash == received_hash:
# Write the file content to the file
with open(file_name, 'wb') as file:
file.write(file_content)
print(f"File '{file_name}' received and saved successfully.")
# Send acknowledgment to the client
client_socket.send("ACK".encode())
def handle_client(client_socket):
# Call the receive_file function to handle file receiving
receive_file(client_socket)
# Close the client socket
client_socket.close()
def main():
# Create a server socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the server socket to the specified host and port
server.bind((HOST, PORT))
# Listen for incoming connections
server.listen()
print("Server waiting for connections...")
while True:
# Accept a client connection
client_socket, client_address = server.accept()
print(f"Connection accepted from {client_address}")
# Create a new thread to handle the client
client_thread = threading.Thread(target=handle_client, args=(client_socket,))
client_thread.start()
main()
````
您的代码在块中使用了同名“文件”描述符两次:
# Write the received file content to a file
with open(file_name, 'wb') as file:
# Check if the calculated hash matches the received hash
if calculated_hash == received_hash:
# Write the file content to the file
with open(file_name, 'wb') as file:
file.write(file_content)
print(f"File '{file_name}' received and saved successfully.")
# Send acknowledgment to the client
client_socket.send("ACK".encode())
尝试改变它:
# Check if the calculated hash matches the received hash
if calculated_hash == received_hash:
# Write the file content to the file
with open(file_name, 'wb') as file:
file.write(file_content)
print(f"File '{file_name}' received and saved successfully.")
# Send acknowledgment to the client
client_socket.send("ACK".encode())