Private/ConvertTo-MultipartContent.ps1

function ConvertTo-MultipartContent {
    <#
    .SYNOPSIS
        Builds the multipart/form-data body of an upload.

    .DESCRIPTION
        Ghost takes an upload as a form with the file in the part named file, next to text fields such as
        purpose. Windows PowerShell cannot build such a form itself, so the bytes are put together here, the same
        way on every PowerShell version.

        The text fields come first, ordered by name, and the file comes last. The result holds the bytes and the
        content type, which carries the boundary that separates the parts. Pass both to Submit-Request.

    .EXAMPLE
        ConvertTo-MultipartContent -Fields @{ purpose = 'image' } -FileName 'a.png' -FileContent $bytes

        Returns an object with the properties Content and ContentType for a form with one field and the file.
    #>

    [CmdletBinding()]
    [OutputType([pscustomobject])]
    param(
        # The text fields of the form: name = value.
        [System.Collections.IDictionary] $Fields = @{},

        # The name the file is sent under.
        [Parameter(Mandatory)]
        [string] $FileName,

        # The content of the file.
        [Parameter(Mandatory)]
        [byte[]] $FileContent,

        # The content type of the file, such as image/png.
        [string] $FileContentType = 'application/octet-stream',

        # The text that separates the parts. Defaults to a new, random one.
        [ValidatePattern('^[A-Za-z0-9-]{1,70}$')]
        [string] $Boundary = ('GhostFormBoundary{0}' -f [guid]::NewGuid().ToString('N'))
    )

    # A quote or a line break would end the header the name is written in.
    $safeName = ($FileName -replace '[\r\n]').Replace('"', '%22')

    $utf8 = [System.Text.UTF8Encoding]::new($false)
    $stream = [System.IO.MemoryStream]::new()
    try {
        foreach ($name in $Fields.Keys | Sort-Object) {
            $part = @(
                "--$Boundary"
                "Content-Disposition: form-data; name=`"$name`""
                ''
                [string] $Fields[$name]
                ''
            ) -join "`r`n"
            $bytes = $utf8.GetBytes($part)
            $stream.Write($bytes, 0, $bytes.Length)
        }

        $header = @(
            "--$Boundary"
            "Content-Disposition: form-data; name=`"file`"; filename=`"$safeName`""
            "Content-Type: $FileContentType"
            ''
            ''
        ) -join "`r`n"
        $bytes = $utf8.GetBytes($header)
        $stream.Write($bytes, 0, $bytes.Length)
        $stream.Write($FileContent, 0, $FileContent.Length)

        $bytes = $utf8.GetBytes(("`r`n--{0}--`r`n" -f $Boundary))
        $stream.Write($bytes, 0, $bytes.Length)

        $content = $stream.ToArray()
    }
    finally {
        $stream.Dispose()
    }

    [pscustomobject]@{
        Content     = $content
        ContentType = 'multipart/form-data; boundary={0}' -f $Boundary
    }
}