Python脚本向Laravel后端上传文件失败,请求数据为空
问题:Python上传文件至Laravel后端失败,服务器无法获取文件参数
我尝试通过Python脚本向Laravel后端上传文件,但文件未成功上传至服务器。服务器端$request->all()返回空数组,$request->has('file')返回false。相同接口在Insomnia REST中可正常工作。
服务器端代码
- api.php
Route::post('upload-file', UploadFilesController::class);
- UploadFilesController
class UploadFilesController extends Controller { /** * Handle the incoming request. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function __invoke(Request $request) { return response()->json($request->all()); // 获取到空数组,使用$request->hasFile('file')也返回false } }
客户端Python脚本
import requests # Set the API endpoint URL url = "http://127.0.0.1:8000/api/upload-file" # Set the file to be uploaded file_path = "/path/to/file.pdf" # Set the content type to "multipart/form-data" headers = {'Content-Type': 'application/x-www-form-urlencoded'} # Read the file and create the form data with open(file_path, 'rb') as f: file_data = {'file': f} # Send the POST request to the API endpoint response = requests.post(url, headers=headers, files=file_data) # Print the response from the server print(response.text)
我也曾替换为headers = {'Content-Type': 'multipart/form-data'},但仍然无法解决问题。
问题原因
问题核心在于手动设置Content-Type请求头。当使用requests.post()的files参数上传文件时,requests库会自动生成包含边界标识符(boundary)的multipart/form-data请求头——这个边界是服务器解析请求体的关键。手动设置Content-Type会覆盖自动生成的头,要么格式错误(比如application/x-www-form-urlencoded完全不适合文件上传),要么缺少必要的boundary,导致Laravel无法识别请求中的文件参数。
解决方案
删除手动设置的headers参数,让requests自动处理Content-Type。如果需要添加其他请求头(如认证令牌),仅保留必要字段,不要包含Content-Type。
修正后的Python脚本:
import requests url = "http://127.0.0.1:8000/api/upload-file" file_path = "/path/to/file.pdf" # 无需手动设置Content-Type with open(file_path, 'rb') as f: file_data = {'file': f} # 移除headers参数,或仅添加非Content-Type的请求头 response = requests.post(url, files=file_data) print(response.text)
若需添加其他头(比如认证),示例如下:
headers = {'Authorization': 'Bearer your-auth-token'} response = requests.post(url, headers=headers, files=file_data)
测试修正后的脚本,服务器端即可正常获取file参数,$request->hasFile('file')会返回true,$request->all()也会包含文件相关信息。
内容的提问来源于stack exchange,提问作者Faizan Aalam
相关产品推荐
相关产品推荐

