You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell调用Telerik Report Server API上传报表失败求助

PowerShell上传Telerik报表服务器报错排查与修复

问题场景

使用PowerShell调用Telerik报表服务器V2 REST API上传报表时,其他GET/POST接口均正常,但上传报表的POST请求始终返回验证错误,提示必填字段缺失,尽管请求Body中已包含这些字段。

原代码

$headers = @{
    "Accept"="application/json"; 
    "Content-Type"="application/x-www-form-urlencoded"
    "Authorization"="bearer 4X8k++++" }

$httpfile = @{
    Name="$rptName";
    FileName="$rptFileName";
    MediaType="application/x-zip-compressed";
    Buffer="$( Get-Content "$rptFullname" -AsByteStream )";
} 

$rptbody = [PSCustomObject]@{
    Name="$rptName";
    Description="$rptDescription";
    CategoryId="$categoryId"; 
    ReportFile = $httpfile
} | ConvertTo-Json

Write-Debug " ----------rptBody"
$rptBody | Write-Debug 
Write-Debug " ----------"

irm "$($base_uri)/api/reportserver/v2/reports" -Method POST -Headers $headers -Body $rptBody

生成的请求Body

{
  "Name": "rpt1",
  "Description": "uploaded on 08.Aug.23",
  "CategoryId": "04044ss3f4",
  "ReportFile": {
    "Name": "rpt1",
    "FileName": "rpt1.trdp",
    "MediaType": "application/x-zip-compressed",
    "Buffer": "80 75 3 4 2 ++++" 
  } 
}

返回错误

{ "Message": "The request is invalid.",
"ModelState": { "model.Name": [ "The Name field is required."],
"model.CategoryId": [ "The CategoryId field is required." ],
"model.ReportFile": [ "The ReportFile field is required." ] } }

问题根源

根据Telerik报表服务器V2 REST API规范,上传报表的POST请求有两个核心要求被原代码违反:

  1. 内容类型错误:API要求使用multipart/form-data提交表单数据,而非application/x-www-form-urlencoded或JSON
  2. 文件上传方式错误:报表文件需以文件流形式作为表单字段提交,不能将字节序列化为JSON中的Buffer字段传递

修复后的代码

$headers = @{
    "Accept"="application/json"; 
    "Authorization"="bearer 4X8k++++"
}

# 构建符合要求的表单数据
$formData = @{
    Name          = $rptName
    Description   = $rptDescription
    CategoryId    = $categoryId
    ReportFile    = Get-Item -Path $rptFullname
}

# 发送POST请求,PowerShell会自动处理multipart/form-data格式
Invoke-RestMethod -Uri "$($base_uri)/api/reportserver/v2/reports" `
                  -Method POST `
                  -Headers $headers `
                  -Form $formData

关键修复说明

  • 移除了手动设置的Content-Type头,使用-Form参数时,PowerShell会自动添加正确的multipart/form-data类型及边界参数
  • 直接通过Get-Item获取文件对象,PowerShell会自动处理文件的流式上传,无需手动读取字节流或构造Buffer字段
  • 不再将数据序列化为JSON,而是通过表单字段的方式提交,完全匹配API的参数要求

内容的提问来源于stack exchange,提问作者Flightdeck73

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 18:45:02