[MVC控制器尝试使用Axios与FormData发送POST时收到空数据

问题描述 投票:1回答:1

我似乎无法找出为什么我的控制器接收空数据的原因。我可以到达控制器,但是没有数据传输。当我使用Postman使用Body和正确的密钥/数据内容测试API时,在控制器端一切正常。

enter image description here

我的控制器方法:

[Route("home/api/files")]
public class FileController : ControllerBase
{
  [HttpPost]
  public async Task<IActionResult> Post([FromForm] FileModel file)
  {
    if (file == null)
      return BadRequest("Given data is null");
    if (string.IsNullOrEmpty(file.Name))
      return BadRequest("File name is undefined");
    if (string.IsNullOrEmpty(file.FolderPath))
      return BadRequest("FolderPath is undefined");
    if (file.File.Length < 0)
      return BadRequest("File content is empty");
    ...
  }
}

文件模型:

public class FileModel
{
  public string Name { get; set; }
  public string Extension { get; set; }
  public string FolderPath { get; set; }
  public IFormFile File { get; set; }
}

和客户端Axios调用:

export function uploadFile(folderPath, data) {
  console.log("upLoadFile", folderPath, data);

  const formData = new FormData();
  formData.set('name', data.file);
  formData.set('extension', data.extension);
  formData.set('folderPath', folderPath);
  formData.append('file', data);

  return axios.post(
    "api/files",
    formData,
    { headers: { 'Content-Type': 'multipart/form-data}' }})
    //{ headers: { 'Content-Type': 'multipart/form-data; boundary=${form._boundary}' }})
    .then((response) => {
      console.log(response.data);
      console.log(response.status);
    })
    .catch((error) => {
      console.log(error);
    });
}

我认为问题出在我要发送的数据类型上?尤其是对于服务器模型定义的类型为File的属性IFormFile。欢迎所有想法!

javascript c# axios asp.net-core-2.0
1个回答
1
投票

我相信主要的问题与我最初尝试的数据类型有关。给定的data必须采用正确的格式/类型,这一点很重要。

按照以下说明正确定义数据:

const file = new Blob([data.contents], { type: 'text/csv' });

const formData = new FormData();
formData.set('Name', data.file);
formData.set('Extension', data.extension);
formData.set('FolderPath', folderPath);
formData.append('File', file);

const requestConfig = {
    headers: {
    "Content-Type": "multipart/form-data"
  }
};

formData的定义如上,以下Axios POST可以正常工作,而控制器没有问题或更改,[FromForm]可以正常工作。

return axios.post(
  "api/files",
  formData,
  requestConfig)
.then((response) => {
  console.log(response.data);
})
.catch((error) => {
  console.log(error);
});
© www.soinside.com 2019 - 2024. All rights reserved.