Post 立即服务中的附件

Post attachment in Service Now

我对如何让它发挥作用感到困惑。 在 Postman 中,我可以毫无问题地上传附件。 我正在上传一个简单的文本文件。 邮递员的代码显示了这一点:

var form = new FormData();
form.append("uploadFile", "C:\temp\test.txt");

var settings = {
  "async": true,
  "crossDomain": true,
  "url": "https://xxxxxxx.service-now.com/api/now/attachment/file?table_name=problem&table_sys_id=oiui5346jh356kj3h634j6hk&file_name=Toast",
  "method": "POST",
  "headers": {
    "Accept": "application/json",
    "Content-Type": "application/x-www-form-urlencoded",
    "Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==",
    "Cache-Control": "no-cache",
    "Postman-Token": "39043b7f-8b2c-1dbc-6a52-10abd25e91c1"
  },
  "processData": false,
  "contentType": false,
  "mimeType": "multipart/form-data",
  "data": form
}

$.ajax(settings).done(function (response) {
  console.log(response);
});

当我在 .asp 页面上使用它时,我收到 400 错误和来自控制台的响应: "Failed to create the attachment. File part might be missing in the request." 如何将要附加到代码中的文件正确获取。我认为硬编码会奏效。你如何获得在本地用户电脑上查找文件的代码。一旦我开始工作,我最终想要一个文件输入按钮 select 文件。

谢谢, 斯科特

你的代码看起来不错,除了这一行:

form.append("uploadFile", "C:\temp\test.txt");

将文件名作为第二个参数传递是行不通的,根据FormData.appendhere的文档,你需要传递一些blob/file指向文档的对象self(不是字符串)

现在有两种可能的情况:

场景一

用户使用浏览按钮手动选择文件

在这里,您需要将输入添加到您的页面,并在选择文件时触发上传文件,如下所示:

uploadDataFile();

function uploadDataFile(fileInput) {
  // creates the FormData object
  var form = new FormData();
  // get the first file in the file list of the input 
  // (you will need a loop instead if the user will select many files)
  form.append("uploadFile", fileInput.files[0]);
  // ... the rest of your AJAX code here ...
}
<input type="file" onchange="uploadDataFile(this)" />

场景二

无需用户干预直接上传文件

这里你需要像这里一样手动构造文件对象answer然后你将它正常添加到你的数据对象

function uploadDataFile() {
  // creates the file object
  var fileObject = new File (...);
  // creates a data object and appends the file object to it
  var form = new FormData();
  form.append("uploadFile", fileObject);
  // ... the rest of your AJAX code here ...
}

最后一个音符

请注意 FormData & File 对象的浏览器兼容性