无法从Axios(vue-nuxt)将文件发送到.net核心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
推荐答案
由于使用了错误的URL,您会收到404错误.
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能够作为 multipart/form-data
请求正确处理 FormData
.您无需设置标头(无论如何还是不正确的),也不必将 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核心API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!