使用Python Requests与Flask传输exe文件时出现文件损坏问题
解决Flask接收POST上传exe文件损坏的问题
你的代码存在两处核心问题,导致exe文件传输后损坏:
问题1:发送端文件上传格式错误
你直接将f.read()的二进制内容作为files字典的值,不符合requests文件上传的规范。files参数需要接收文件对象,或包含文件名、内容、MIME类型的元组,这样requests才能正确生成multipart/form-data格式的请求,保证二进制数据完整传输。
问题2:服务器端接收逻辑错误
你用request.form["file"]获取文件内容是完全错误的:request.form仅用于处理表单文本数据,而文件上传必须用request.files。另外,对二进制内容执行encode("utf-8")会把非UTF-8兼容的字节(exe文件大量存在)强制转码,直接破坏文件结构。
修正后的发送端代码
import requests, shutil targeturl = "http://127.0.0.1:5000/latest" with open("client_copy.exe", "rb") as f: # 正确传递文件对象,requests会自动处理上传格式 files = {"file": f} response = requests.post(targeturl, files=files) shutil.copyfile("client_copy.exe", "client.exe") print(f"Request Sent. Response code: {response.status_code}. {response.reason}")
修正后的Flask服务器代码
from flask import request, send_file import os @app.route("/latest", methods=["GET", "POST"]) def latest(): if request.method == "GET": path = os.path.join(os.getcwd(), "client.exe") return send_file(path, as_attachment=True) elif request.method == "POST": uploaded_file = request.files.get("file") if not uploaded_file: return "No file uploaded", 400 # 直接读取二进制内容写入文件,跳过错误的编码步骤 with open("client.exe", "wb") as file: file.write(uploaded_file.read()) return "Success", 200 else: return f"Error: {request.method} is not a valid method. Use GET or POST.", 405
内容的提问来源于stack exchange,提问作者cycooYT
相关产品推荐
相关产品推荐

