我一直在尝试在 PowerShell 中构建一些代码(PowerShell 6 Core 有效,以下代码在 PowerShell 5 中无效),
$Token = ' Token Here ';
$Headers = @{
Method = 'POST'
Uri = ' URL Here '
Headers = @{Authorization = "Bearer $Token" }
}
$bodyHere = @{
roomId = ' ChatSpace ID Here '
text = ' Some Random Text '
files = Get-Item -Path 'c:\test.png'
}
try {
Invoke-RestMethod @Headers -Form $bodyHere
} catch [System.Net.WebException] {
Write-Error $_.Exception.ToString()
throw $_
}
这很好用并且可以上传文件,但是我还需要添加Content-Type: "image/png"
到我的Get-Item
项目中 - 有没有简单的方法可以做到这一点?
Add-Member
我还尝试通过构建多部分表单来以另一种方式做到这一点,我已经看到其他人在 StackOverflow 上使用过,但是我现在遇到另一个问题,当我尝试使用或使用任何其他表单时,我无法添加到多部分表单中追加到表单的方法。
$Token = ' Token Here ';
$Headers = @{
Method = 'POST'
Uri = ' URL Here '
Headers = @{Authorization = "Bearer $Token" }
}
$bodyLines = @{
roomId = ' ChatSpace ID Here '
text = ' Random Text here '
}
$FilePath = 'c:\test.png'
$FieldName = 'files'
$ContentType = 'image/png'
$FileStream = [System.IO.FileStream]::New($filePath, [System.IO.FileMode]::Open)
$FileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::New('form-data')
$FileHeader.Name = $FieldName
$FileHeader.FileName = Split-Path -Leaf $FilePath
$FileContent = [System.Net.Http.StreamContent]::New($FileStream)
$FileContent.Headers.ContentDisposition = $FileHeader
$FileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse($ContentType)
$MultipartContent = [System.Net.Http.MultipartFormDataContent]::New()
$MultipartContent.Add($FileContent)
$MultipartContent.Add($bodyLines) # this doesn't work as I'm building a multipart form
$MultipartContent | Add-Member -Name "headers" -Value $bodyLines -MemberType NoteProperty # I convert this to JSON and use write-host but it doesn't append I've also tried $MultipartContent.headers and it still doesn't append
try {
# Invoke-RestMethod @Headers -Body $MultipartContent
Invoke-WebRequest @Headers -Body $bodyLines
} catch [System.Net.WebException] {
Write-Error $_.Exception.ToString()
throw $_
}
对于如何使用文件上传和其他参数构建多部分表单或将内容类型附加到 Get-Item 调用的任何帮助,将不胜感激。只是为了让您了解 Python 中的代码是什么样的(容易得多):
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
m = MultipartEncoder({'roomId': ' ChatSpace ID Here ',
'text': ' Random Text Here ',
'files': ('example.png', open('example.png', 'rb'),
'image/png')})
r = requests.post(' URL Here ', data=m,
headers={'Authorization': 'Bearer TokenHere',
'Content-Type': m.content_type})
print r.text