WebApi Code
public IHttpActionResult UploadFiles()
{
try
{
var request = HttpContext.Current.Request;
if (request.Files.Count <= 0)
{
return StatusCode(HttpStatusCode.NoContent);
}
//Define files storage location
string basePath = AppDomain.CurrentDomain.BaseDirectory + "Uploads\\";
if (!Directory.Exists(basePath))
{
Directory.CreateDirectory(basePath);
}
for (int i = 0; i < request.Files.Count; i++)
{
try
{
var file = request.Files[i];
file.SaveAs(basePath + file.FileName);
}
catch (Exception ex)
{
}
}
return Ok();
}
catch (Exception ex)
{
return BadRequest();
}
}
Xamarin Code
private async void Upload_Click(object sender, EventArgs e)
{
try
{
if (SelectedFiles == null)
{
return;
}
//MultipartFormDataContent : support select multiple files
MultipartFormDataContent contents = new MultipartFormDataContent();
//foreach the selected files and add it to contents
foreach (var item in SelectedFiles)
{
//File Content(Stream) , name , FileName
contents.Add(new StreamContent(await item.OpenReadAsync()), "file", DateTime.Now.ToString("yyyyMMddHHmmss") + item.FileName);
}
//Post,Pass contents to WebApi
var rs = await new HttpClient().PostAsync("UploadFiles", contents);
//Verify reulst after WebApi processing
if (rs .IsSuccessStatusCode)
{
await DisplayAlert("Tips","Success!","OK");
}else
await DisplayAlert("Tips","Error!","OK");
}
catch (Exception ex)
{
}
}
Xamarin Select File Code
public IEnumerable<FileResult> SelectedFiles { get; set; }
public async void SelectFiles()
{
//Select Multiple Files ,The File Type is Image
SelectedFiles = await FilePicker.PickMultipleAsync(PickOptions.Images);
}