PowerShell POST请求失败:无法向Google Cloud Function上传文件
问题分析与解决
问题背景
原可正常运行的curl命令:
curl -X POST -F "file=@C:\your\file\location\Example.csv" -H "Authorization: Bearer [INSERT BEARER TOKEN]" https://example-api-or-endpoint.com
转换后的PowerShell代码执行失败:
$uri = "https://example-api-or-endpoint.com" $outputCsvPath = "C:\your\file\location\Example.csv" $headers = @{"Authorization" = "Bearer [BEARERTOKEN]"} Invoke-WebRequest -Uri $uri -Method Post -InFile $outputCsvPath -ContentType "multipart/form-data" -Headers $headers
预期返回:
{"file_id":"FILEID","message":"File sent successfully","status":"success"}
实际返回:
{"message":"No file part in the request","status":"error"}
已尝试Invoke-RestMethod、替换InFile为Body,确认文件路径/存在性,问题仍存在,目标端点为Google Cloud Function(GCF),需上传完整文件而非内容。
问题原因
curl的-F "file=@xxx"是将文件作为multipart/form-data表单的file字段上传,但PowerShell的Invoke-WebRequest -InFile只是直接将文件内容作为请求体发送,并未构造包含字段名的表单结构,导致GCF无法识别请求中的文件部分。
解决方法
需要手动构造multipart/form-data表单,指定file字段并添加文件内容,代码示例:
$uri = "https://example-api-or-endpoint.com" $filePath = "C:\your\file\location\Example.csv" $token = "[INSERT BEARER TOKEN]" # 构造multipart表单内容 $multipartContent = [System.Net.Http.MultipartFormDataContent]::new() $fileStream = [System.IO.FileStream]::new($filePath, [System.IO.FileMode]::Open) $fileContent = [System.Net.Http.StreamContent]::new($fileStream) # 指定表单字段名为"file",并设置文件名 $multipartContent.Add($fileContent, "file", (Split-Path $filePath -Leaf)) # 添加Authorization头 $headers = @{"Authorization" = "Bearer $token"} # 发送请求 try { $response = Invoke-RestMethod -Uri $uri -Method Post -Body $multipartContent -Headers $headers $response | ConvertTo-Json } catch { Write-Error $_.Exception.Message } finally { # 释放资源 $fileStream.Dispose() $fileContent.Dispose() $multipartContent.Dispose() }
关键说明
- 使用
System.Net.Http.MultipartFormDataContent正确构造带字段名的表单,匹配curl的-F行为 - 必须指定表单字段名为
file,与curl命令中的字段名一致 - 通过
StreamContent读取文件流,确保上传完整文件 - 最后记得释放流和内容对象,避免资源泄漏
内容的提问来源于stack exchange,提问作者Seph Rodriguez
相关产品推荐
相关产品推荐

