【问题标题】:PowerShell equivalent for cURL command uploading filecURL 命令上传文件的 PowerShell 等效项
【发布时间】:2013-04-22 00:21:16
【问题描述】:

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

curl -i -F file=@file.txt http://www.website.com/put_file

服务器需要来自 $_FILES['file'] 的文件。

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

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

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

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

【问题讨论】:

  • 我最终下载了适用于 windows 的 curl 可执行文件,效果非常好!

标签: windows post powershell curl http-post


【解决方案1】:

我觉得应该是这样的:

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

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

【讨论】:

  • curl's -F is 一个多部分/表单数据 POST,所以我猜这个答案的大部分是......不准确
【解决方案2】:

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

curl.exe -i -F file=@file.txt http://www.website.com/put_file

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

有关来自 powershell 3 的 Invoke-RestMethod 的更多详细信息:https://superuser.com/questions/344927/powershell-equivalent-of-curl

【讨论】:

  • 这不是 OP 要求的。
  • 对不起@WarrenP,但他要求'PowerShell 等效于 cURL 命令',即 curl.exe 并且包含的​​链接指向该问题的确切答案并解决了他的问题
  • 您链接到的链接提供了 Invoke-RestMethod 的可接受答案:
【解决方案3】:

为了解决这个问题,我下载了windows的curl.exe,仍然使用curl。

【讨论】:

  • 这种事情最好作为对您的问题的编辑。
【解决方案4】:

在使用 fiddler 尝试匹配 curl 几个小时后,我放弃了,只使用了这个家伙的功能(见下面的链接)。像魅力一样工作。

http://blog.majcica.com/2016/01/13/powershell-tips-and-tricks-multipartform-data-requests/

【讨论】:

    猜你喜欢
    • 2013-02-02
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    相关资源
    最近更新 更多