I'm trying to receive an image from Xamarin Forms on Android in my ASP.NET Core MVC web page (written in C#).
My Xamarin.form
code:
var file = await MediaPicker.PickPhotoAsync();
if (file == null)
return;
var content = new MultipartFormDataContent();
content.Add(new StreamContent(await file.OpenReadAsync()), "file", file.FileName);
var httpClient = new HttpClient();
String url = "http://urlMyWeb/";
httpClient.BaseAddress = new Uri(url);
var response = await httpClient.PostAsync("", content);
if (response.IsSuccessStatusCode)
{
lblStatus.Text = "successful upload";
}
else
{
lblStatus.Text = "upload failed";
}
ASP.NET Core MVC web app HomeController
code:
[HttpPost]
public async Task<ActionResult> UploadFile(IFormFile file)
{
try
{
if (file.Length > 0)
{
string _FileName = Path.GetFileName(file.FileName);
string _path = Path.Combine(Directory.GetCurrentDirectory(), "Images", _FileName);
using (var stream = new FileStream(_path, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
ViewBag.Message = "File uploaded successfully!";
return View();
}
catch
{
ViewBag.Message = "File upload failed";
return View();
}
}
I am trying to save the image that I sent from Xamarin Forms to my server in a folder called Images
. I tried this code but I can't make it work.
When I sent the file, Xamarin responds with "successful upload". So, it sent the image, but I never receive it in the ASP.NET Core web app.
How could I resolve this?
Thank you very much!