Now i'm doing project on Xamarin.Forms in Visual Studio 2017. i'm trying to upload image using HttpClient and post file through php code to my server directory. But the code below here still not working.
I can get photo and show on my application but can not upload to server!
Please help!
C# file
async Task GetPhoto(Func<Task<MediaFile>> getPhotoFunc)
{
IsEnabled = false;
try
{
var photo = await getPhotoFunc();
if (photo == null)
return;
Image = null;
AllPredictions = new List<PredictionModel>();
Image = SKBitmap.Decode(photo.GetStreamWithImageRotatedForExternalStorage());
await PredictPhoto(photo);
IsEnabled = true;
byte[] bitmapData;
var stream = new MemoryStream();
photo.GetStream().CopyTo(stream);
bitmapData = stream.ToArray();
var fileContent = new ByteArrayContent(bitmapData);
fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = "image_test.jpg"
};
string boundary = "---8393774hhy37373773";
MultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary);
multipartContent.Add(fileContent);
HttpClientHandler clientHandler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(clientHandler);
HttpResponseMessage response = await httpClient.PostAsync("http://it2.sut.ac.th/project61_g23/php/upload-image.php", multipartContent);
response.EnsureSuccessStatusCode();
}
catch (Exception ex)
{
Crashes.TrackError(ex, new Dictionary<string, string> { { "Action", "Getting predictions" } });
await Application.Current.MainPage.DisplayAlert("Error", $"An error occured: {ex.Message}", "OK");
}
finally
{
IsEnabled = true;
}
}
PHP code
<?php
$uploaddir = '/Uploads/';
$uploadfile = $uploaddir.basename($_FILES['file']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
} else {
echo "Possible file upload attack!\n";
}
echo 'Here is some more debugging info:';
print_r($_FILES);
echo '</pre>';
?>