如何使用 PowerShell Invoke-RestMethod 发送多部分/表单数据 [英] How to send multipart/form-data with PowerShell Invoke-RestMethod

查看:39
本文介绍了如何使用 PowerShell Invoke-RestMethod 发送多部分/表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过 Invoke-RestMethod 在与 curl 类似的上下文中使用 -F 开关发送文件.

I'm trying to send a file via Invoke-RestMethod in a similar context as curl with the -F switch.

卷曲示例

curl -F FileName=@"/path-to-file.name" "https://uri-to-post"

在 powershell 中,我尝试过这样的事情:

In powershell, I've tried something like this:

$uri = "https://uri-to-post"
$contentType = "multipart/form-data"
$body = @{
    "FileName" = Get-Content($filePath) -Raw
}

Invoke-WebRequest -Uri $uri -Method Post -ContentType $contentType -Body $body
}

如果我检查 fiddler,我会看到正文包含原始二进制数据,但我收到 200 响应,显示没有发送有效负载.

If I check fiddler I see that the body contains the raw binary data, but I get a 200 response back showing no payload has been sent.

我也尝试过使用 -InFile 参数,但没有成功.

I've also tried to use the -InFile parameter with no luck.

我已经看到了许多使用 .net 类的示例,但我试图使用较新的 Powershell 3 命令保持简单.

I've seen a number of examples using a .net class, but was trying to keep this simple with the newer Powershell 3 commands.

有没有人有任何指导或经验来完成这项工作?

Does anyone have any guidance or experience making this work?

推荐答案

这里的问题是 API 需要一些额外的参数.初始请求需要一些参数来接受原始内容并指定文件名/大小.设置并取回正确的链接提交后,我可以使用:

The problem here was what the API required some additional parameters. Initial request required some parameters to accept raw content and specify filename/size. After setting that and getting back proper link to submit, I was able to use:

Invoke-RestMethod -Uri $uri -Method Post -InFile $filePath -ContentType "multipart/form-data"

这篇关于如何使用 PowerShell Invoke-RestMethod 发送多部分/表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆