根据 ServiceNow 文档,我们可以通过两种方式通过 Rest Api 将文件上传到 ServiceNow : https://developer.servicenow.com/dev.do#!/reference/api/xanadu/rest/c_AttachmentAPI#attachment-POST-file
当前遵循 api/now/attachment/file ,将指定的二进制文件作为附件上传到指定的记录。 注意:附加的文件必须在传入的请求参数列表中最后一个参数之后指定。
如何在下面的代码中设置二进制文件,以便之后可以使用现有的通用方法 CreateRecord 来上传它
private async Task UploadAttachment(CRMContext crmContext, ServiceNowAttachment attachment, ServiceNowQueryOptions requestOptions)
{
if (attachment.FileData != null && attachment.FileData.Length > 0)
{
using var fileContent = new ByteArrayContent(attachment.FileData);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); // Adjust MIME type if needed
content.Add(fileContent, "file", attachment.FileName!);
} --how to send the content?
JObject? additionalFields = null; // not used for CreateAttachment
// Create the record using CreateRecord
await this.serviceNowClient.CreateRecord<ServiceNowAttachment>(
crmRequestContext,
attachment,
additionalFields, // No additional fields for attachment
requestOptions).ConfigureAwait(false);
}
这样怎么上传呢?根据约束,CreateRecord 参数无法更改,因此我们只需像这样发送附件/文件
要使用 CreateRecord 方法上传二进制文件而不修改其参数,您可以利用 HttpClient 允许您将多部分表单数据作为请求的一部分发送的事实。您可以遵循以下一般方法在现有代码中实现此目的:
以下是如何调整 UploadAttachment 方法以遵循此方法:
private async Task UploadAttachment(CRMContext crmContext, ServiceNowAttachment attachment, ServiceNowQueryOptions requestOptions)
{
if (attachment.FileData != null && attachment.FileData.Length > 0)
{
// Create a multipart form content to hold the file and other form fields
using var content = new MultipartFormDataContent();
// Add the file as byte array content
var fileContent = new ByteArrayContent(attachment.FileData);
fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); // Adjust MIME type if needed
// Add fileContent to multipart content with a form field name of 'file'
content.Add(fileContent, "file", attachment.FileName!);
// CreateRecord should handle sending the multipart content as the request body
JObject? additionalFields = null; // not used for CreateAttachment
// Create the record using the existing CreateRecord method
await this.serviceNowClient.CreateRecord<ServiceNowAttachment>(
crmContext,
attachment,
additionalFields, // No additional fields for attachment
requestOptions).ConfigureAwait(false);
}
}