According to
https://stackoverflow.com/a/14413414
Natively WebAPI doesn't support binding of multiple POST parameters.
Here I already gave two examples of WebAPI with multiple Post parameters. Now I will use similiar approach to send image plus additional data, like file and folder name.
First don't forget in Program.cs to add Service:
builder.Services.AddMvc().AddNewtonsoftJson();
Controller:
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
namespace UploadImageServer.Controllers;
public class UploadImageController : Controller
{
[HttpPost]
[Route("UploadImage")]
public async Task<IActionResult> UploadImage([FromBody] JObject? data)
{
if (data is null) return BadRequest(new { message = "No image." });
string? base64Image = data["image"]?.ToString();
if (base64Image == null) return BadRequest(new { message = "No image." });
byte[] imageBytes = Convert.FromBase64String(base64Image);
Directory.CreateDirectory(data["folderName"]?.ToString() ?? string.Empty);
string imagePath = $"{data["folderName"]}\\{data["fileName"]}";
await System.IO.File.WriteAllBytesAsync(imagePath, imageBytes);
return Ok(new { message = "Image uploaded successfully." });
}
}
Server download from
here.
---
Client:
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
string imageUrl = "spring.jpg";
string base64Image = ConvertImageToBase64(imageUrl);
var jsonData = new JObject
{
["image"] = base64Image
, ["fileName"] = "magnolia.jpg"
, ["folderName"] = "spring"
};
string jsonContent = jsonData.ToString();
using HttpClient client = new HttpClient();
StringContent content = new StringContent(jsonContent);
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
HttpResponseMessage response = await client.PostAsync("https://localhost:7028/UploadImage", content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine("Image uploaded successfully!");
}
else
{
Console.WriteLine("Failed to upload image. Status code: " + response.StatusCode);
}
static string ConvertImageToBase64(string imagePath)
{
byte[] imageBytes = File.ReadAllBytes(imagePath);
return Convert.ToBase64String(imageBytes);
}
Client download from
here.