CodexBloom - Programming Q&A Platform

PowerShell 7.3 - implementing Using Invoke-RestMethod for File Upload with Multipart/Form-Data

๐Ÿ‘€ Views: 33 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-12
PowerShell API Invoke-RestMethod FileUpload

I tried several approaches but none seem to work. I've been researching this but I tried several approaches but none seem to work... I'm trying to upload a file to a REST API endpoint using PowerShell 7.3, but I'm working with issues with the `Invoke-RestMethod` command while trying to send the file as `multipart/form-data`. The API expects the file to be included in the request body, but I'm not sure how to properly format the request. Hereโ€™s the code Iโ€™m currently using: ```powershell $filePath = 'C:\path\to\your\file.txt' $apiUrl = 'https://api.example.com/upload' # Create the form data $formData = @{ 'file' = Get-Item $filePath } # Attempt to upload the file $response = Invoke-RestMethod -Uri $apiUrl -Method Post -Form $formData ``` When I run this code, I receive the following behavior: ``` Invoke-RestMethod : The request body must contain a valid form data payload. ``` Iโ€™ve also tried using `-ContentType 'multipart/form-data'` but that hasnโ€™t resolved the scenario. I've verified that the API endpoint is working correctly using Postman, where I can upload the same file without any problems. I suspect that the way I'm packaging the file in the form data may not be correct for PowerShell. Is there a recommended way to structure the file upload in PowerShell to ensure the format matches what the API expects? Any help would be greatly appreciated! This is part of a larger application I'm building. I'm open to any suggestions. Is this even possible?