【问题标题】:Upload file with Powershell使用 Powershell 上传文件
【发布时间】:2019-05-20 03:58:29
【问题描述】:

我正在尝试在 Powershell 中创建一个等效于

的命令

curl -u username:abcd -i -F name=files -F filedata=@employees.csv https://myservice.com/v1/employees/csv

我需要在请求中包含文件名。所以在 Powershell 中

$FilePath = 'employees.csv'
$FieldName = 'employees.csv'
$ContentType = 'text/csv'
$username = "user"
$password = "..."

$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)

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($username):$($password)" ))
$Response = Invoke-WebRequest -Headers @{Authorization = "Basic $base64AuthInfo" } -Body $MultipartContent -Method 'POST' -Uri 'https://myservice.com/v1/employees/csv'

有没有更好(更短)的方法来让我在 Content Disposition 中有一个文件名?

$body = get-content employees.csv -raw
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("user:pass" ))
Invoke-RestMethod -Headers @{Authorization = "Basic $base64AuthInfo" } -uri url -Method Post -body $body -ContentType 'text/csv
# a flag -ContentDispositionFileName would be great

【问题讨论】:

  • 查看Invoke-RestMethod 的文档。你做了很多额外的工作。
  • 我查看了文档,但我没有足够的 Powershell-foo。我可以看到我可以改进两件事。使用 -Credentials 而不是 -Headers(不知道如何创建 Credential 对象)。使用带有-Form的文件对象来设置文件名(同样的问题)

标签: powershell file http curl mime-types


【解决方案1】:

猜测您的端点将接受什么,但这是您在powershell 中的curl 请求示例:

$u, $p = 'username', 'password'
$b64 = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("${u}:$p"))
$invokerestmethodParams = @{
    'Uri'             = 'https://myservice.com/v1/employees/csv'
    'Method'          = 'POST'
    'Headers'         = @{ Authorization = "Basic $b64" }
    'InFile'          = 'C:\path\to\employees.csv'
    'SessionVariable' = 's' # use $s to view content headers, etc.
}
$output = Invoke-RestMethod @invokerestmethodParams

【讨论】:

  • 发出标准 curl 请求不是问题,但正如我所说,我需要在 ContentDisposition 中设置文件名。
  • @LukaszMadon ContentDisposition 是什么意思?您在问题的任何地方都没有这么说。
  • "我需要在请求中包含文件名。" curl 推断 filenameContent-Disposition: form-data; name="employees.csv"; filename="employees.csv" developer.mozilla.org/en-US/docs/Web/HTTP/Headers/…。在 Powershell 中,我似乎必须做整个 $FileContent.Headers.ContentDisposition 没有标志。
猜你喜欢
  • 1970-01-01
  • 2017-11-16
  • 2016-12-08
  • 2010-12-24
  • 2017-02-11
  • 1970-01-01
  • 2014-05-15
  • 2022-09-30
相关资源
最近更新 更多