Created
December 10, 2019 11:16
-
-
Save arichika/91a8b1f60c87512401e320a614099283 to your computer and use it in GitHub Desktop.
POST multiple files with multipart/form-data with PowerShell v5 / PowerShell v5 で 複数ファイルを multipart/form-data で POST する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
################################################################## | |
## POST multiple files with multipart/form-data with PowerShell v5 | |
################################################################## | |
## POST Uri | |
$uri = "https://localhost/" | |
## Consts | |
$successFiles = './success' | |
$tempFile = './tempfile' | |
$UTF8woBOM = New-Object "System.Text.UTF8Encoding" -ArgumentList @($false) | |
$boundary = '----BCA246E0-E2CF-48ED-AACE-58B35D68B513' | |
## Init | |
Remove-Item $tempFile -Force -ErrorAction Ignore | |
## Find Files e.g. *.csv | |
$files = Get-ChildItem * -File -Include *.csv | |
foreach($file in $files) | |
{ | |
Write-Host $file.FullName | |
$sw = New-Object System.IO.StreamWriter($tempFile, $true, $UTF8woBOM) | |
$fileName = [System.IO.Path]::GetFileName($file.FullName) | |
$sw.Write("--$boundary`r`nContent-Disposition: form-data;name=`"files`";filename=`"$fileName`"`r`n`r`n") | |
$sw.Close() | |
$fs = New-Object System.IO.FileStream($tempFile, [System.IO.FileMode]::Append) | |
$bw = New-Object System.IO.BinaryWriter($fs) | |
$fileBinary = [System.IO.File]::ReadAllBytes($file.FullName) | |
$bw.Write($fileBinary) | |
$bw.Close() | |
} | |
$sw = New-Object System.IO.StreamWriter($tempFile, $true, $UTF8woBOM) | |
$sw.Write("`r`n--$boundary--`r`n") | |
$sw.Close() | |
## Go POST | |
try { | |
if(($files | Measure-Object).Count -gt 0) | |
{ | |
Invoke-RestMethod -Method POST -Uri $uri -ContentType "multipart/form-data; boundary=$boundary" -InFile $tempFile | |
} | |
} catch { | |
Write-Host "StatusCode:" $_.Exception.Response.StatusCode.value__ | |
Write-Host "StatusDescription:" $_.Exception.Response.StatusDescription | |
exit 1 | |
} | |
## Finale | |
New-Item $successFiles -itemType Directory -Force | |
Get-ChildItem * -File -Include *.csv | Move-Item -Destination $successFiles -Force | |
Remove-Item $tempFile -Force | |
exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment