ServiceNow Utah版本附件上传API调用报错求助
问题描述
我尝试在ServiceNow Utah版本中,将一个文本文件上传至一篇未发布的知识文章,使用的PowerShell代码如下:
$uri = "https://instanceName.service-now.com/api/now/attachment/upload" $method = "POST" $filePath = "C:\it\test.txt" $headers = @{ "Accept" = "application/json" } $uploadResult = Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Credential $credential -ContentType "multipart/form-data" -Form @{ "table_name" = "kb_knowledge" "table_sys_id" = "fcd86f8fc314b5500240d1ec7a01319f" # 文章的Sys_id,文件将附加到该文章 "uploadFile" = Get-Item -Path $filePath }
已确认$credential对应的账号具备添加附件权限(可创建知识文章),但执行后报错:
Invoke-RestMethod: {"error":{"message":"Missing parameter: table_name","detail":null},"status":"failure"}
尝试给表单字段值添加双引号(单引号结果相同),修改后的代码:
$uploadResult = Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Credential $credential -ContentType "multipart/form-data" -Form @{ table_name = "`"kb_knowledge`"" table_sys_id = "`"fcd86f8fc314b5500240d1ec7a01319f`"" # 文章的Sys_id,文件将附加到该文章 uploadFile = "`"$(Get-Item -Path $filePath)`"" }
执行后出现新错误:
Invoke-RestMethod: {"error":{"message":"Failed to create the attachment. File part might be missing in the request.","detail":null},"status":"failure"}
确认C:\it\test.txt文件存在,使用/upload而非/file接口是为了避免处理文件MIME类型,请问问题出在哪里?
问题原因及解决方法
核心问题
- 手动指定
-ContentType "multipart/form-data"破坏了PowerShell的自动表单处理:使用Invoke-RestMethod的-Form参数时,PowerShell会自动生成正确的multipart/form-data请求头(包括边界标识)。手动指定该参数会导致表单字段无法被ServiceNow正确解析,触发Missing parameter: table_name错误。 - 额外引号导致参数和文件对象无效:给字段值添加引号后,
table_name会被识别为带引号的字符串(如"kb_knowledge"),不符合接口要求;将Get-Item结果转为带引号的字符串,会丢失文件对象的原始属性,导致接口无法识别文件部分,出现文件缺失错误。
修正后的代码
$uri = "https://instanceName.service-now.com/api/now/attachment/upload" $filePath = "C:\it\test.txt" $headers = @{ "Accept" = "application/json" } $uploadResult = Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Credential $credential -Form @{ "table_name" = "kb_knowledge" "table_sys_id" = "fcd86f8fc314b5500240d1ec7a01319f" "uploadFile" = Get-Item -Path $filePath }
关键说明
- 移除
-ContentType "multipart/form-data"参数,让PowerShell自动处理表单请求的Content-Type和边界。 - 保持表单字段值的原始格式,不要额外添加引号,
uploadFile直接传递Get-Item返回的文件对象即可。 - 确认目标知识文章的
sys_id正确,且账号对该未发布文章拥有编辑/添加附件的权限(即使能创建文章,也需验证对指定文章的权限)。
内容的提问来源于stack exchange,提问作者StackExchangeGuy
相关产品推荐
相关产品推荐

