使用Invoke-RestMethod上传文件遇ContentLength错误,TransferEncoding不支持怎么办?
解决Invoke-RestMethod上传文件时的ContentLength错误问题
我之前踩过一模一样的坑!用PowerShell调用REST API传文件时,ContentLength的处理确实容易出问题,尤其是服务器不支持分块编码(TransferEncoding: chunked)的情况下。下面给你几个亲测有效的解决方案:
方法一:手动读取文件字节并指定ContentLength
这个方法最直接,先把文件读成字节数组,准确计算出内容长度后再传给请求,从根源避免PowerShell自动计算长度出错的问题:
# 1. 读取文件为字节数组,获取准确的内容长度 $filePath = "C:\your\file\path\example.pdf" $fileBytes = [System.IO.File]::ReadAllBytes($filePath) $contentLength = $fileBytes.Length # 2. 构造请求头(注意根据文件类型设置正确的Content-Type) $headers = @{ "Content-Type" = "application/pdf" # 比如图片用image/png,文本用text/plain } # 3. 调用API,明确指定ContentLength参数 try { $response = Invoke-RestMethod -Uri "https://your-upload-endpoint.com/api/upload" ` -Method Post ` -Headers $headers ` -Body $fileBytes ` -ContentLength $contentLength Write-Host "上传成功!响应:$response" } catch { Write-Host "上传失败:$($_.Exception.Message)" }
方法二:用HttpClient替代Invoke-RestMethod(更灵活)
如果Invoke-RestMethod的封装限制太多,用.NET原生的HttpClient会更可控,它能自动处理ContentLength的计算,也避免了TransferEncoding的问题:
$httpClient = New-Object System.Net.Http.HttpClient # 构造文件内容 $fileContent = New-Object System.Net.Http.ByteArrayContent([System.IO.File]::ReadAllBytes("C:\your\file\path\example.jpg")) $fileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("image/jpeg") # 发送请求 try { $response = $httpClient.PostAsync("https://your-upload-endpoint.com/api/upload", $fileContent).Result $response.EnsureSuccessStatusCode() # 检查请求是否成功 $responseBody = $response.Content.ReadAsStringAsync().Result Write-Host "上传成功!响应:$responseBody" } catch { Write-Host "上传失败:$($_.Exception.Message)" } finally { # 记得释放资源 $httpClient.Dispose() $fileContent.Dispose() }
方法三:处理表单上传(multipart/form-data)
如果你的API要求用表单上传(比如接收字段名为file的文件),用MultipartFormDataContent会更合适,它会自动处理各部分的ContentLength:
$httpClient = New-Object System.Net.Http.HttpClient $multipartContent = New-Object System.Net.Http.MultipartFormDataContent # 添加文件内容,注意第三个参数是服务器接收的文件名,第二个是表单字段名 $fileContent = New-Object System.Net.Http.ByteArrayContent([System.IO.File]::ReadAllBytes("C:\your\file\path\example.txt")) $fileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse("text/plain") $multipartContent.Add($fileContent, "file", "uploaded-file.txt") try { $response = $httpClient.PostAsync("https://your-upload-endpoint.com/api/form-upload", $multipartContent).Result $responseBody = $response.Content.ReadAsStringAsync().Result Write-Host "表单上传成功!响应:$responseBody" } catch { Write-Host "上传失败:$($_.Exception.Message)" } finally { $httpClient.Dispose() $multipartContent.Dispose() $fileContent.Dispose() }
关键注意点:
- 一定要根据文件类型设置正确的
Content-Type,服务器通常会校验这个字段,传错可能导致上传失败。 - 避免使用
-TransferEncoding Chunked,大部分传统服务器都不支持分块编码的上传请求。
内容的提问来源于stack exchange,提问作者irl_irl
相关产品推荐
相关产品推荐

