我是新来的 Requestbody 发送表单数据,其中包括从我的手机媒体上传图像和一些字符串格式的数据。我在 Postman 中使用过它并且它正在工作,但在我的应用程序中我遇到了一个问题,即在将数据发布到 API 时它会发出 400 个错误请求。这是我的代码。任何帮助都可以
这是我的后端 api 代码。
[HttpPost]
public ActionResult<FishReadDTO> CreateFish([FromForm] FishCreateDTO fishCreateDTO)
{
var fishmodel = _mapper.Map<Fish>(fishCreateDTO);
if(fishCreateDTO.ImageFile.Length > 0 || fishCreateDTO.ImageFile != null)
{
string apiServerAddress = _httpContextAccessor.HttpContext.Request.Scheme + "://"
+ _httpContextAccessor.HttpContext.Connection.LocalIpAddress.MapToIPv4().ToString()
+ ":" + _httpContextAccessor.HttpContext.Connection.LocalPort;
try
{
if(!Directory.Exists(_webHostEnvironment.WebRootPath + "\\images\\"))
{
Directory.CreateDirectory(_webHostEnvironment.WebRootPath + "\\images\\");
}
using (FileStream filestream = System.IO.File.Create(_webHostEnvironment.WebRootPath + "\\images\\" + fishCreateDTO.ImageFile.FileName))
{
fishCreateDTO.ImageFile.CopyTo(filestream);
filestream.Flush();
fishmodel.Image = apiServerAddress + "/images/" + fishCreateDTO.ImageFile.FileName;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error Occured {ex.Message}");
}
}
_repository.CreateFish(fishmodel);
var fishRead = _mapper.Map<FishReadDTO>(fishmodel);
return CreatedAtRoute(nameof(GetFishById), new{Id = fishRead.ID}, fishRead);
}
这是我的 Fish Create DTO。
public class FishCreateDTO
{
[Required]
[MaxLength(50)]
public string Name { get; set; }
[MaxLength(100)]
public string Description { get; set; }
[Required]
public float WeightKg { get; set; }
[Required]
public int Stock { get; set; }
[Required]
public float Price { get; set; }
[Required]
public int CategoryID { get; set; }
[Required]
public int UserID { get; set; }
public IFormFile ImageFile {get; set;}
}
对于前端,我使用的是 android Kotlin,它也涉及 Retrofit2。
这是api调用
@Multipart
@POST("/efishing-api/fish")
suspend fun createFish(
@Part("name") name: String,
@Part("description") description : String,
@Part("weightKG") weightKG: String,
@Part("stock") stock : String,
@Part("price") price : String,
@Part("categoryID") categoryID: String,
@Part("userID") userID : String,
@Part imageFile : MultipartBody.Part
) : FishCreateResponse
这是存储库。
suspend fun createFish(
name : String,
description : String,
weightKG : String,
stock : String,
price : String,
userId: String,
categoryId: String,
imageFile : MultipartBody.Part
) : FishCreateResponse {
return RetrofitBuilder.apiService.createFish(
name,
description,
weightKG,
stock,
price,
categoryId,
userId,
imageFile
)
}
这是我正在使用的视图模型
fun createFish(
name : String,
description : String,
weightKG : String,
stock : String,
price : String,
userId: String,
categoryId: String,
imageFile : MultipartBody.Part
) {
CoroutineScope(IO).launch {
val fishCreate = fishRepository.createFish(
name,
description,
weightKG,
stock,
price,
categoryId,
userId,
imageFile
)
}
}
这是我尝试上传表单数据的地方
val file = File(filePath)
val requestBody = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
fishViewModel.createFish(
Fishname.text.toString(),
Description.text.toString(),
FishPrice.text.toString(),
Weight.text.toString(),
Stock.text.toString(),
categoryID.toString(),
userId.toString(),
MultipartBody.Part.createFormData("imageFile", file.name, requestBody)
)
这是日志猫
2021-07-20 01:49:31.117 24404-25371/com.example.efishingapp E/AndroidRuntime: FATAL EXCEPTION: DefaultDispatcher-worker-3
Process: com.example.efishingapp, PID: 24404
retrofit2.HttpException: HTTP 400 Bad Request
at retrofit2.KotlinExtensions$await$2$2.onResponse(KotlinExtensions.kt:53)
at retrofit2.OkHttpCall$1.onResponse(OkHttpCall.java:161)
at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:519)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:923)
*更新(我的改造)
@Multipart
@POST("/efishing-api/fish")
suspend fun createFish(
@Part("name") name: String,
@Part("description") description : String,
@Part("weightKG") weightKG: String,
@Part("stock") stock : String,
@Part("price") price : String,
@Part("categoryID") categoryID: String,
@Part("userID") userID : String,
@Part imageFile : MultipartBody.Part
) : FishCreateResponse
任何解决方案都可以。谢谢