无法从 Axios (vue-nuxt) 向 .net core API 发送文件 [英] Can not send file to the .net core API from Axios (vue-nuxt)
问题描述
如果我尝试将文件从 Vue 发送到 .net Core 中的 API 端点,我会收到 500 个错误
I get back 500 errors if i try to send a file from Vue to my API endpoint in .net Core
我遵循了执行此操作的教程,但它们似乎不适用于此设置.
I followed tutorials who do this, but they do not seem to work for this setup.
.net 核心 API:
.net core API:
[Route("api/[controller]")]
[ApiController]
public class FileUploadController : ControllerBase
{
[HttpPost("[Action]")]
public string sendFiles([FromBody]FileUploadAPI file)
{
return "Yes!";
}
public class FileUploadAPI
{
public IFormFile File { get; set; }
}
}
Vue:
this.$axios.post(
'https://localhost:44352/api/fileupload/sendFiles',
event.target.files[0],
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
我想在 API 中接收我的文件请求失败,状态码为 500
I want to receive my file in the API Request failed with status code 500
推荐答案
您会收到 404 错误,因为您使用了错误的 URL.
You would get a 404 error because you're using the wrong URL.
您的操作名称是 sendFiles
(复数),因此正确的 URL 路径应该是 /api/FileUpload/sendFiles
.
Your action name is sendFiles
(plural) so the correct URL path would be /api/FileUpload/sendFiles
.
Axios 能够将 FormData
作为 multipart/form-data
请求正确处理.您不需要设置标题(无论如何都是不正确的),也不应该将 data
包装在一个对象中.
Axios is capable of handling FormData
correctly as a multipart/form-data
request. You do not need to set headers (which were incorrect anyway), nor should you wrap the data
in an object.
let data = new FormData();
data.append('file', files[0]); // assuming "files" refers to a FileList
this.$axios.post('https://localhost:44352/api/FileUpload/sendFiles', data)
.then(...)
这篇关于无法从 Axios (vue-nuxt) 向 .net core API 发送文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!