gpt4 book ai didi

http - 从 Powershell 脚本上传多个文件

转载 作者:可可西里 更新时间:2023-11-01 15:08:55 25 4
gpt4 key购买 nike

我有一个网络应用程序可以像这样处理 HTML 表单的 POST:

<form action="x" method="post" enctype="multipart/form-data">
<input name="xfa" type="file">
<input name="pdf" type="file">
<input type="submit" value="Submit">
</form>

注意有两个type="file" <input>元素。

如何从 Powershell 脚本编写 POSTing 脚本?我计划这样做是为了为该服务创建一个简单的测试框架。

我找到了 WebClient.UploadFile() , 但它只能处理单个文件。

感谢您抽出宝贵时间。

最佳答案

我今天一直在使用 PowerShell 制作多部分 HTTP POST。希望下面的代码对您有所帮助。

  • PowerShell 本身不能进行多部分表单上传。
  • 关于它的样本也不多。我根据 this 构建了代码和 this .
  • 当然,Invoke-RestMethod 需要 PowerShell 3.0,但上述链接后面的代码显示了如何直接使用 .NET 执行 HTTP POST,从而使您也可以在 Windows XP 中运行它.

祝你好运!请告诉你是否让它工作。

function Send-Results {
param (
[parameter(Mandatory=$True,Position=1)] [ValidateScript({ Test-Path -PathType Leaf $_ })] [String] $ResultFilePath,
[parameter(Mandatory=$True,Position=2)] [System.URI] $ResultURL
)
$fileBin = [IO.File]::ReadAllBytes($ResultFilePath)
$computer= $env:COMPUTERNAME

# Convert byte-array to string (without changing anything)
#
$enc = [System.Text.Encoding]::GetEncoding("iso-8859-1")
$fileEnc = $enc.GetString($fileBin)

<#
# PowerShell does not (yet) have built-in support for making 'multipart' (i.e. binary file upload compatible)
# form uploads. So we have to craft one...
#
# This is doing similar to:
# $ curl -i -F "file=@file.any" -F "computer=MYPC" http://url
#
# Boundary is anything that is guaranteed not to exist in the sent data (i.e. string long enough)
#
# Note: The protocol is very precise about getting the number of line feeds correct (both CRLF or LF work).
#>
$boundary = [System.Guid]::NewGuid().ToString() #

$LF = "`n"
$bodyLines = (
"--$boundary",
"Content-Disposition: form-data; name=`"file`"$LF", # filename= is optional
$fileEnc,
"--$boundary",
"Content-Disposition: form-data; name=`"computer`"$LF",
$computer,
"--$boundary--$LF"
) -join $LF

try {
# Returns the response gotten from the server (we pass it on).
#
Invoke-RestMethod -Uri $URL -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -TimeoutSec 20 -Body $bodyLines
}
catch [System.Net.WebException] {
Write-Error( "FAILED to reach '$URL': $_" )
throw $_
}
}

关于http - 从 Powershell 脚本上传多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25075010/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com