使用PowerShell或cURL上传文件时遇服务器400错误求助
解决方案:修复CSV上传的400 Bad Request(NOT_MULTIPART错误)
问题根源
错误result_code=NOT_MULTIPART明确说明服务器要求请求采用multipart/form-data格式(即表单上传),但你的脚本直接将文件内容作为请求体发送,Content-Type不符合服务器的接收要求。
PowerShell修正脚本
使用Invoke-RestMethod的-Form参数构建符合要求的multipart请求,同时携带认证令牌:
$file = "c:\folder\file.csv" $machinetoken = $companySettings.EncryptionToken $endpoint = "https://site/upload/files" # 构建表单数据,文件字段名需和服务器要求一致(通常为"file") $form = @{ file = Get-Item $file } try { $response = Invoke-RestMethod -Method Post -Uri $endpoint -Headers @{ "Authorization" = $machinetoken } -Form $form Write-Host "上传成功:$($response | ConvertTo-Json)" } catch { $errorMessage = $_.Exception.Message $responseBody = $null if ($_.Exception.Response) { $reader = New-Object System.IO.StreamReader($_.Exception.Response.GetResponseStream()) $reader.BaseStream.Position = 0 $reader.DiscardBufferedData() $responseBody = $reader.ReadToEnd() } Write-Error "上传失败:$errorMessage`n响应内容:$responseBody" }
cURL修正脚本
使用-F参数指定表单字段,替代原有的-InFile参数:
$file = "c:\folder\file.csv" $machinetoken = $companySettings.EncryptionToken curl -Uri https://site/upload/files -Method Post -H "Authorization: $machinetoken" -F "file=@$file" -Verbose
关键注意事项
- 表单字段名(示例中的
file)必须和服务器接口文档要求一致,若服务器指定其他名称(比如csv_upload),需对应修改。 - 确认
$machinetoken的格式符合服务器要求:如果服务器要求认证头带Bearer前缀,需将头信息改为"Authorization: Bearer $machinetoken"。
内容的提问来源于stack exchange,提问作者Brian Lind Eriksen
相关产品推荐
相关产品推荐

