当我使用 cURL.exe 运行以下命令来上传文件时,我没有任何问题:
Curl.exe -X POST -H "X-API-TOKEN: token here" -F file=@"E:\program files\curl\filetoupload.csv"
https://url.com/files
我需要从脚本运行它,所以我想我会使用 PowerShell 的 Invoke-WebRequest。当我运行以下代码时,我得到
Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send.
At E:\Scripts\Celero\qualtrics.ps1:8 char:13
+ $response = Invoke-WebRequest -Headers $headers -Method Post -OutFile ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-
WebRequest], WebException
+ FullyQualifiedErrorId :
WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand"
$filepath = "e:\program files\curl\filetoupload.csv"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("X-API-TOKEN", "token here")
$urlAPI = "https://url.com/files"
$response = Invoke-WebRequest -Headers $headers -Method 'Post' -OutFile $filepath -URI $urlAPI
我试过添加
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12,[Net.SecurityProtocolType]::Tls11
和
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12
没有运气。有任何想法吗?
更新 我最终在 PowerShell 中执行此操作:
param ($curlExe, $filepath, $headers,$qualtricsAPI,$jobfile)
try{
Copy-Item $jobfile -Destination $filepath
$upload = & $curlExe -X POST -H $headers -s -o -w "%{http_code}" -F file=@$filepath $qualtricsAPI
if ($upload -match "200 - OK"){
Write-Host "Upload successful."
Write-Host "Response: "$upload
Remove-Item $filepath
Write-Host "File removed from $($filepath)."
exit 0
}else{
Write-Host "Upload not successful"
Write-Host "Response: "$upload
exit 2
}
}catch{
"Exception Message: $($_.Exception.Message)"
exit 1
}
我已经使用我们的文件传输自动化工具对其进行了测试,并且成功了。我在 Invoke-WebRequest cmdlet 上旋转我的轮子。