【发布时间】:2022-01-19 21:21:00
【问题描述】:
我需要将用户输入作为 JSON 数据和文件发送到 API 端点。我可以单独发送每一个,但我一生都无法弄清楚如何同时发送。
我的 API 端点读取每一个都很好,但是在一起调试时,请求永远不会通过 Axios 发布调用。
我已经尝试了许多测试来实现这一点,但到目前为止都没有成功。
*编辑 原来一半的问题出在服务器端。使用 .Net 5 API,我使用 IFormFile 文件和 UserMetaData 数据作为参数。我发现一篇文章在模型中创建所有 POCO 并使用它。反而。我现在可以使用 POSTMAN 正确接收文件和数据,但是当来自 axios 时它现在为空。这是控制器供参考
[HttpPost]
[Route("user-upload")]
public async Task<IActionResult> UserUpload([FromForm] UserMetaData userData)
{
var result = " You sent the value " + userData;
return Ok(userData.UserFile.FileName);
}
现在令人沮丧的是,当我通过 axios 发送相同的数据时,它会到达控制器并且它为空。我已经验证了数据在到达之前就在那里。谁能看到我错过的东西?
这里有一些代码要显示:
Test Object
let inputTest = {
dataOwner: this.name,
deviceSerialNumber: this.deviceSerialNumber,
dataDistribution: this.distribution,
}
// New FormData to append file and user data
let formData = new FormData();
//File input
for (let files of this.file) {
formData.append("userFile", files);
}
//User data
formData.append("userData", JSON.stringify(inputTest));
//Axios call
this.axios.post('API endpoint URL',
formData,{
header: {
'Content-Type': 'multipart/form-data',
'Accept': 'application/json'
},
}
).then(response =>{ console.log(response)}).catch(error =>{ alert(error)})
我尝试过同时更改标题和内容类型,也可以单独更改。没有运气。
我在发帖时收到此错误:
**status: 415**
**title: "Unsupported Media Type"**
我不想单独发送这些,因为它们完全没有应用程序的需求。
感谢您的帮助
【问题讨论】:
-
@match,不幸的是它没有。我尝试了他们在那里展示的内容,但仍然无法获得任何更改。
-
即使您以相同的方式使用
axios,即不设置headers? -
是的,这就是我输入的内容 - this.axios.post('URL', formData, ).then(response =>{ console.log(response)}).catch(error => {警报(错误)})..