我正在嘗試將 img 檔案從用 React/Typescript 撰寫的前端傳遞給用 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."]}
所以我想,我要么以錯誤的方式傳遞檔案,要么模型不正確,不應該是位元組 []。
對于解決此問題的最佳方法,我將不勝感激!
uj5u.com熱心網友回復:
您可以將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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/516221.html
上一篇:如何在不使用兩個名稱的情況下簡潔地匯出包裝和命名的函式
下一篇:TS介面中的可選和必需屬性