将文件从REACT/TYPESCRIPT传递到C#API会导致错误:“无法将JSON值转换为System.Byte[]”

brgchamk  于 2022-10-21  发布在  React
关注(0)|答案(1)|浏览(295)

我正在尝试将一个img文件从用Reaction/TypeScrip编写的前端传递到用C#编写的API。
以下是使用Axios处理上传照片和将状态上传到C#API的函数:

const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {

        const files = event.target.files as FileList
        const file = files[0] as File

        setRecipeData((prev) => {
            return {...prev, RecipePhoto: file}
        })
    }
    const handleRecipeUpload = () => {

        axios.post('https://localhost:7104/api/Recipe/Post', recipeData)
        .then((response) => {
            console.log(response)
        })
        .catch((error) => {
            console.log(error)
            console.log(JSON.stringify(error.response.data.errors));
        })
    }

这是我用C#编写的控制器

[HttpPost]
        [Route("Post")]
        public async Task<IActionResult> PostRecipeAsync(PostRecipeDto postRecipeDto)
        {
            return Ok(await _postRecipeServices.PostRecipeService(postRecipeDto));
        }

和DTO的模型:

public class PostRecipeDto
    {
        public string? Name { get; set; }
        public string? Description { get; set; }
        public string? Country { get; set; }
        public string? IngridientList { get; set; }
        public int CookingTimeInMins { get; set; }
        public byte[]? RecipePhoto { get; set; }
    }

在尝试上传时,我在浏览器控制台中遇到的错误是:

{"postRecipeDto":["The postRecipeDto field is required."],"$.RecipePhoto":["The JSON value could not be converted to System.Byte[]. Path: $.RecipePhoto | LineNumber: 0 | BytePositionInLine: 155."]}

所以我猜,我要么是以错误的方式传递文件,要么是模型不正确,不应该是byte[]。
我会极力推荐任何关于解决这个问题的最佳方法的建议!

e5nqia27

e5nqia271#

您可以将handleRecipeUpload方法更改为如下所示

const handleRecipeUpload = () => {
     const formData = new FormData();
formData.append('RecipePhoto', recipeData.RecipePhoto);
// append all other properties of `recipeData`
.
.
.
const config = {
  headers: {
    'content-type': 'multipart/form-data',
  },
};
    axios.post('https://localhost:7104/api/Recipe/Post', formData, config)
    .then((response) => {
        console.log(response)
    })
    .catch((error) => {
        console.log(error)
        console.log(JSON.stringify(error.response.data.errors));
    })
}

在C#端,将类PostRecipeDto更改如下--

public class PostRecipeDto
{
    public string? Name { get; set; }
    public string? Description { get; set; }
    public string? Country { get; set; }
    public string? IngridientList { get; set; }
    public int CookingTimeInMins { get; set; }
    public IFormFile? RecipePhoto { get; set; }
}

要从IFormFile中获取字节,您可以参考以下链接--
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.iformfile?view=aspnetcore-6.0

相关问题