【问题标题】:.net core Cannot deserialize the current JSON array into type 'Microsoft.AspNetCore.Http.IFormFile'.net core 无法将当前 JSON 数组反序列化为“Microsoft.AspNetCore.Http.IFormFile”类型
【发布时间】:2020-07-09 16:11:50
【问题描述】:

我正在尝试上传图片,通过前端发送图片(axios请求),然后服务器返回这个错误。

无法将当前 JSON 数组反序列化为类型 'Microsoft.AspNetCore.Http.IFormFile' 因为该类型需要 JSON 要正确反序列化的对象。要修复此错误,请更改 JSON 到 JSON 对象(例如 {"name":"value"})或更改 将类型反序列化为数组或实现集合的类型 接口(例如 ICollection、IList),例如 List 可以 从 JSON 数组反序列化。也可以添加 JsonArrayAttribute 强制它从 JSON 数组反序列化的类型。路径“文件”, 第 1 行,位置 339。”

    [HttpPost("add")]
    public async Task<IActionResult> Add(Post post, IFormFile file){............}

这是我的 axios 请求

  const submit = useCallback(
    async (values: PostExtensions) => {
      debugger;
      setLoading(true);

      const tarih = dayjs(values.date);
      values.tarih = dayjs(date, "YYYY-MM-DDTHH:mm:ss Z").format();

      const formdata = new FormData();
      formdata.append("postId", values.postId!);
      formdata.append("file", values.file![0]);
      formdata.append("userId", values.userId!);
      formdata.append("projectId", values.projectId!);
      formdata.append("date", values.date!);

      await entitySubmit({
        values: JSON.parse(JSON.stringify(values)),
        dispatch: dispatch,
        returndata: true,
        headers: {
          "Content-Type": "multipart/form-data"
        },
        links: [
          {
            type: 0,
            link: "post/addpost",
            actionType: ActionType.add_Post,
            method: "POST",
          },
          {
            type: 1,
            link: "post/editpost",
            actionType: ActionType.edit_Post,
            method: "POST",
          },
        ],
        id: "postId",
      });
      return null;
    },
    [show, dispatch]
  );

当我尝试发布表单数据时,它没有提交。

EDIT 1:我发现问题出在哪里, formData 发送类似这样的空文件对象

formdata.get('file') // '[Object object]'

【问题讨论】:

  • 首先尝试从邮递员或任何 api 测试软件中访问该 api,然后移动以使用前端语言使用该 api。
  • 如何测试在邮递员或其他什么上发布图像文件?
  • 可以显示上传文件的axios代码吗?从错误中,我猜你正在尝试将它作为 JSON 发布,它应该作为多部分上传发布
  • 当我尝试多部分表单数据的内容类型时,我收到此错误“无法读取请求表单。缺少内容类型边界。”

标签: c# json asp.net-core


【解决方案1】:

不是您问题的直接答案,但我发现使用 base64 编码时,通过 ajax 发送文件通常要容易得多。以下是您如何实现此目的的一个小示例:

//client side
//this function converts a file object to a base64 string
const toBase64 = file => new Promise((resolve, reject) => {
   const reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = () => resolve(reader.result);
   reader.onerror = error => reject(error);
});

document.getElementById("upload").onclick = async () => {
    const file = document.getElementById('myfile').files[0];
    const base64 = await toBase64(file);
    const response = await fetch('/home/upload', {
        method: 'post',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify( {base64 /*add any additional values you need here */})
})
    const json = await response.json();
}

//server side
public class UploadData
{
    public string Base64Data { get; set; }
    //any additional properties you need here....
}

[HttpPost]
public IActionResult Upload([FromBody]UploadData data)
{
    var base64 = data.Base64Data.Substring(data.Base64Data.IndexOf(",") + 1); //bit of a hack, need to remove the additional part of the base64 string that JS generates but that .net doesn't like
    var bytes = Convert.FromBase64String(base64);
    //bytes is now available to do whatever you need with
    return Json(someObjectYouWantToReturn);
}

希望这段代码能成为一个足够好的起点,让您到达您需要的地方。同样,base64 可能不是您所追求的,但我经常使用这种方法,我个人觉得处理起来很简单。

【讨论】:

    猜你喜欢
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 2013-07-19
    • 1970-01-01
    • 2019-03-18
    • 1970-01-01
    • 2019-03-20
    相关资源
    最近更新 更多