我现在左右为难,不知道该怎么做。在Postman中,我可以毫无问题地上传附件。我正在上传一个简单的文本文件。postmanshows中的代码显示了以下内容:
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错误和来自控制台的响应:“无法创建附件。请求中可能缺少文件部分。”如何将你想要的文件正确地附加到代码中。我以为用硬编码应该行得通。如何获得在本地用户pc上查找该文件的代码。一旦我得到了这个工作,我最终希望有一个文件输入按钮来选择文件。
谢谢,斯科特
发布于 2018-06-09 05:58:49
您的代码看起来很好,除了下面这一行:
form.append("uploadFile", "C:\\temp\\test.txt");
将文件名作为第二个参数传递是行不通的,根据FormData.append
here的文档,您需要传递一些指向文档本身的blob/file对象(而不是字符串)
现在有两种可能的情况:
场景1
用户使用浏览按钮手动选择文件
在这里,您需要将输入添加到您的页面中,并在选中文件时添加一个触发器来上传该文件,如下所示:
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)" />
场景2
无需用户干预,直接上传文件
在这里,您需要像在此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
对象的浏览器兼容性
https://stackoverflow.com/questions/50743579
复制相似问题