我正在尝试在 ExtJS 和 Web API 中上传文件。为此,我需要向服务器发送一个授权标头,但每当我尝试这样做时,我都会在标头中得到一个空值。我还尝试在
beforerequest
函数中发送带有 XHR 请求的标头,但我仍然得到一个空值。
这是代码:
Ext.Ajax.request({
url: 'url',
method: 'Post',
headers : {'Authorization':'Bearer '+access_token},
form: form,
isUpload: true,
params: {id: id},
我在某处读到,不可能在表单提交中发送标头。那么有什么方法可以实现我的目标吗?
您可以像这样使用FormData对象和XMLHttpRequest来上传文件:
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
var formData = new FormData();
for (var i= 0; i< files.length; i++) {
var file = files[i];
formData.append(file.name, file);
}
xhr.onreadystatechange = function(eOpts) {
if (xhr.readyState !== 4 || me.isDestroyed) {
return;
}
......
};
xhr.send(formData);
更多关于表单数据
很有趣,但我也找不到ExtJS解决方案。
以下示例如何使用 Gabriele Romanato 发布的文件向 POST 请求添加标头:
// Selects the input file from the HTML document
const fileInput = document.getElementById("file-input");
// Creates an XMLHttpRequest instance
const xhr = new XMLHttpRequest();
// We set up the callback to handle the server response
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
// The file has been uploaded successfully
console.log("File successfully uploaded!");
}
};
// We open the connection to the server
xhr.open("POST", "/upload-file", true);
// We set the "Content-Type" header to "multipart/form-data"
xhr.setRequestHeader("Content-Type", "multipart/form-data");
// We create a FormData object and add the selected file
const formData = new FormData();
formData.append("file", fileInput.files[0]);
// We send the request to the server with the send() method
xhr.send(formData);