【发布时间】:2019-02-02 14:04:34
【问题描述】:
现在我正在 Visual Studio 2017 中的 Xamarin.Forms 上做项目。 我正在尝试使用 HttpClient 上传图像并通过 php 代码将文件发布到我的服务器目录。但是下面的代码仍然无法正常工作。
我可以在我的应用程序上获取照片并显示,但无法上传到服务器!
请帮忙!
C# 文件
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 代码
<?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>';
?>
【问题讨论】:
-
HTML 包含您上传的二进制数据中的无效字符。您需要使用 Convert.ToBase64String(string) 将二进制文件转换为 64 位字符串
-
这里有一个关于这个的讨论。你可以参考。forums.xamarin.com/discussion/97078/…
标签: c# xamarin xamarin.forms xamarin.android dotnet-httpclient