首先,确保在安卓端发送的请求中,将图片以正确的格式添加到请求体中。例如:
File file = new File(imagePath);
RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
MultipartBody.Part body = MultipartBody.Part.createFormData("image", file.getName(), requestFile);
接下来,在 .NET REST API 的处理函数中,确保正确地解析请求体并获取图片。例如:
[HttpPost("upload-image")]
public async Task UploadImage([FromForm]IFormFile image)
{
if (image == null)
{
return StatusCode(400, "No image uploaded");
}
// 处理图片...
}
最后,在处理图片的方法中,通过读取图片的流,将其转换为 byte[] 数组,并按需要进行操作。例如:
using (var stream = new MemoryStream())
{
await image.CopyToAsync(stream);
byte[] imageData = stream.ToArray();
// 对图片进行操作...
}