PowerShell等效于cURL命令上传文件

Tak*_*shi 5 windows powershell post curl http-post

我可以使用以下cURL命令将HTTP POST文本文件发送到我的服务器:

curl -i -F file=@file.txt http://www.website.com/put_file
Run Code Online (Sandbox Code Playgroud)

服务器期待来自$ _FILES ['file']的文件.

到目前为止,我有以下内容,但它不起作用:

$url = http://www.website.com/put_file
$file = "c:\file.txt"
$wc = new-object System.Net.WebClient
$wc.UploadFile($url, $file.FullName)
Run Code Online (Sandbox Code Playgroud)

它返回0,并且没有上传到服务器

如何将文件作为$ _FILES ['file']发送?另外,如何从服务器看到响应?

Kei*_*ill 8

我认为它应该是这样的:

$body = "file=$(get-content file.txt -raw)"
Invoke-RestMethod -uri http://www.websetite.com/put_file -method POST -body $body
Run Code Online (Sandbox Code Playgroud)

注意:这确实需要PowerShell V3.此外,您可能需要将-ContentType参数指定为"application/x-www-form-urlencoded".我建议使用Fiddler2并使用它来检查curl和Inovke-RestMethod案例中的请求,以帮助获得正确的irm参数.这假设文件内容相当小且非二进制.如果没有,您可能需要转到内容类型multipart/form-data.

  • curl的-F _is_是一个multipart/form-data POST,所以我猜大多数这个答案都是......不准确 (2认同)

Tro*_*glo 5

在Powershell中,您可以使用curl.exe代替curl(是的,是不同的命令:http://get-cmd.com/?p =5181 )

curl.exe -i -F file=@file.txt http://www.website.com/put_file
Run Code Online (Sandbox Code Playgroud)

或者您可以使用 powershell 3 中的 Invoke-RestMethod

有关 powershell 3 中的 Invoke-RestMethod 的更多详细信息,请访问:https://superuser.com/questions/344927/powershell-equivalent-of-curl

  • 您链接到的链接提供了 Invoke-RestMethod 的可接受答案: (2认同)