通过Powershell Invoke-RestMethod分段上传文件

时间:2020-02-14 06:31:27

标签: python powershell api multipartform-data

我正在尝试通过Powershell使用API​​将文件上传到Webex Teams(消息传递应用程序)。我将其与Python配合使用,但似乎无法使其与Powershell配合使用。不确定我在这里缺少什么。

这是我的 Python代码,它可用于用于上传文件

from requests_toolbelt import MultipartEncoder
import requests
filepath = r'C:\Users\user\Documents\myfile.txt'
filetype = 'text/csv'
roomId = 'Y2lzY2........'
token = 'MDZlM2Ni.......'
url = "https://api.ciscospark.com/v1/messages"
my_fields={'roomId': roomId, 'text': 'Hello World', 'files': ('myfile', open(filepath, 'rb'), filetype)}
m = MultipartEncoder(fields=my_fields)
r = requests.post(url, data=m, headers={'Content-Type': m.content_type, 'Authorization': 'Bearer ' + token})

这是我的 Powershell代码,用于发送消息

$BearerToken = "MDZlM2Ni........."
$SpaceId = "Y2lzY2........."
$body = @{roomId = $SpaceId; text = "Hello World"} | ConvertTo-Json
$Url = "https://api.ciscospark.com/v1/messages"
$Headers = @{"Authorization" = "Bearer $BearerToken"; "Content-Type" = "application/json"}
Invoke-RestMethod -Method POST -Headers $Headers -Uri $Url -Body $body

这是我的 Powershell代码,对于上传文件,该代码不起作用。与上面的Python代码相比,我在这里缺少什么?

$BearerToken = "MDZlM2Ni........."
$SpaceId = "Y2lzY2........."
$body = @{roomId = $SpaceId; text = "Hello World"; files = 'C:\Users\user\Documents\myfile.txt; type=text/csv'} | ConvertTo-Json
$Url = "https://api.ciscospark.com/v1/messages"
$Headers = @{"Authorization" = "Bearer $BearerToken"; "Content-Type" = "multipart/form-data"}
Invoke-RestMethod -Method POST -Headers $Headers -Uri $Url -Body $body

1 个答案:

答案 0 :(得分:0)

我不是python专家,但是看到这两个代码在这里有些歧义。

从服务器收到的任何响应都值得共享,我只是运行了一些命令,这些命令显示正文虽然是json格式,但是文件的路径被视为字符串,这意味着文件是没有附上

{
    "roomId":  "Y2lzY2.........",
    "files":  "C:\\Users\\user\\Documents\\myfile.txt; type=text/csv",
    "text":  "Hello World"
}

以上是我执行代码时正文的输出,因为您可以看到文件中的数据未加载,并且在Python代码中您正在打开文件并将其发送给请求,您可以使用上面提到的代码下面实现该目标

$file = Get-Content C:\sample.txt 
$body = @{roomId = $SpaceId; text = "Hello World"; files=$file+'; type=text/csv'} | ConvertTo-Json
Write-Output $body

这将以纯文本格式加载文件内容,并将其添加到json。

下面的代码正在读取所有字节并将其作为附件附加到正文

$file = Get-ChildItem -Path "C:\\sample.txt"
$file = [System.IO.File]::ReadAllBytes($file.FullName)
$body = @{roomId = $SpaceId; text = "Hello World"; files=$file+'; type=text/csv'} | ConvertTo-Json
Write-Output $body

希望有帮助。