pav*_*lee 7 javascript json multipartform-data file axios
我试图将相同的多部分POST请求中的文件和一些json发送到我的REST端点.该请求直接来自使用axios库的javascript,如下面的方法所示.
doAjaxPost() {
var formData = new FormData();
var file = document.querySelector('#file');
formData.append("file", file.files[0]);
formData.append("document", documentJson);
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
}
Run Code Online (Sandbox Code Playgroud)
但是,问题是当我在网络选项卡中的chrome开发人员工具中检查请求时,我找不到任何Content-Type字段document,而对于file字段Content-Type是application/pdf(我正在发送pdf文件).
在服务器Content-Type上document是text/plain;charset=us-ascii.
更新:
我设法让邮差通过一个正确的请求,通过发送document的.json文件.虽然我发现这只适用于Linux/Mac.
Que*_*tin 27
要设置内容类型,您需要传递类文件对象.您可以使用a创建一个Blob.
const obj = {
hello: "world"
};
const json = JSON.stringify(obj);
const blob = new Blob([json], {
type: 'application/json'
});
const data = new FormData();
data.append("document", blob);
axios({
method: 'post',
url: '/sample',
data: data,
})
Run Code Online (Sandbox Code Playgroud)
小智 18
尝试这个。
doAjaxPost() {
var formData = new FormData();
var file = document.querySelector('#file');
formData.append("file", file.files[0]);
// formData.append("document", documentJson); instead of this, use the line below.
formData.append("document", JSON.stringify(documentJson));
axios({
method: 'post',
url: 'http://192.168.1.69:8080/api/files',
data: formData,
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
}
Run Code Online (Sandbox Code Playgroud)
您可以在后端解码这个字符串化的 JSON。
| 归档时间: |
|
| 查看次数: |
26030 次 |
| 最近记录: |