Invoke-Restmethod multipart/form-data with json and a bin-file

Hello together,

I´m trying to do a multipart/form-data request via powershell.
A query-request with application/json is working but with multipart/form-data I get the following message:
“Invalid Multipart/form request” and I hope you can help me to find the mistake.

This is a example-request from the documentation - only “field_name” is a required field:

----WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="request"; Content-Type: application/json {
"request": {
"md5": "da855ff838250f45d528a5a05692f14e",
"file_name": "MyFile.docx",
"file_type": "docx",
"features": ["te"],
"te": {
"reports": ["pdf", "xml"],
"images": [
"id": "7e6fe36e-889e-4c25-8704-56378f0830df",
"revision": 1
"id": "e50e99f3-5963-4573-af9e-e3f4750b55e2",
"revision": 1
}----WebKitFormBoundary7MA4YWxkTrZu0gW Content-Disposition: form-data; name="file"; filename="MyFile.docx" Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
[Binary content of MyFile.docx] ----WebKitFormBoundary7MA4YWxkTrZu0gW

And this is my code:

$url = "https://foobar/tecloud/api/v1/file/upload"
$boundary = [System.Guid]::NewGuid().ToString()
$file = Get-Item -path $filePath

$mimeType = [System.Web.MimeMapping]::GetMimeMapping($file.Name)

$fileBin = [System.IO.File]::ReadAllBytes($filePath)
#$CODEPAGE = "iso-8859-1"
#$enc = [System.Text.Encoding]::GetEncoding($CODEPAGE)
#$fileEnc = $enc.GetString($fileBin)
$LF = "`r"

$messageBody = @{
    request = @{ 
    file_name = $file.Name
    file_type = "sql"

$bodyLines = (
        'Content-Disposition: form-data; name="request";',
        'Content-Type: application/json',
        (ConvertTo-Json $messageBody)+$LF,
        'Content-Disposition: form-data; name="file"; filename="test.txt"',
		"Content-Type: $mimeType"+$LF,

$Response=Invoke-Restmethod -Uri $url -Method Post -ContentType "multipart/form-data; boundary=$boundary" -Body $bodyLines -verbose

Unfortunately I think constructing multipart MIME messages might be a little beyond what the everyday PowerShell user deals with :). I’m hoping you’ve found an answer for this, but if not, a broader community like StackOverflow might be a good place to look/ask. It’s not really a PowerShell question, is the reason - any programmer needing to manually create a MIME-encoded message would deal with this.