Reputation: 49
I have two projects. One is a Windows Form project, the other one is a .NET Core 2.0 Web API project. I can call my Web API from the Windows Form application and I can make call basic CRUD operations.
I need to POST a photo. How do I do that? My POST looks like that:
private async void AddStudent()
{
var p = new Student
{
FirstName = "Johdn",
LastName = "Doe",
Avatar = "Image"; // my photo
};
using (var client = new HttpClient())
{
var serializedStudent = JsonConvert.SerializeObject(p);
var content = new StringContent(serializedStudent, Encoding.UTF8, "application/json");
var result = await client.PostAsync(URI, content);
}
}
The Web API implementation looks like this:
public void Post([FromBody] Student student)
{
var insideStudent = _dbContext.Students.FirstOrDefault(cus => cus.Id == student.Id);
if (insideStudent != null)
{
insideStudent.FirstName = student.FirstName;
insideStudent.LastName = student.LastName;
_dbContext.SaveChanges();
} else {
_dbContext.Students.Add(new Student
{
FirstName = student.FirstName,
LastName = student.LastName,
Avatar = student.Avatar // my photo
});
_dbContext.SaveChanges();
}
}
But how can I send an image to my Web API?
Upvotes: 1
Views: 1619
Reputation: 2460
MultipartFormDataContent
can be an option. Given that Student.Avatar
is a byte array:
public byte[] Avatar { get; set; }
and you have the stream
of the image, you can send it as byte array content along with string content:
private async void AddStudent()
{
var stream = //gets image stream...
var p = new Student
{
FirstName = "Johdn",
LastName = "Doe",
};
using (var client = new HttpClient())
{
var serializedStudent = JsonConvert.SerializeObject(p);
var stringContent = new StringContent(serializedStudent, Encoding.UTF8, "application/json");
var multipartContent = new MultipartFormDataContent();
using (var mem = new MemoryStream())
{
await stream.CopyToAsync(mem);
var byteContent = new ByteArrayContent(mem.ToArray());
multipartContent.Add(byteContent, "files", "my file");
multipartContent.Add(new StringContent(p.FirstName), "FirstName");
multipartContent.Add(new StringContent(p.LastName), "LastName");
var response = await client.PostAsync(URI, multipartContent);
}
}
}
then you can receive those on server-side:
[HttpPost]
public async void Post([FromForm]Student student)
{
var form = Request.Form;
var insideStudent = _dbContext.Students.FirstOrDefault(cus => cus.Id == student.Id);
if (insideStudent != null)
{
insideStudent.FirstName = student.FirstName;
insideStudent.LastName = student.LastName;
_dbContext.SaveChanges();
}
else
{
var newStudent = new Student
{
FirstName = student.FirstName,
LastName = student.LastName
};
if(form.Files.Any())
{
using (var stream = new MemoryStream())
{
await form.Files[0].CopyToAsync(stream);
newStudent.Avatar = stream.ToArray();
}
}
_dbContext.Students.Add(newStudent);
_dbContext.SaveChanges();
}
}
Upvotes: 1