Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# Xamarin.forms使用php将图像上载到服务器目录_C#_Xamarin_Xamarin.forms_Xamarin.android_Dotnet Httpclient - Fatal编程技术网

C# Xamarin.forms使用php将图像上载到服务器目录

C# Xamarin.forms使用php将图像上载到服务器目录,c#,xamarin,xamarin.forms,xamarin.android,dotnet-httpclient,C#,Xamarin,Xamarin.forms,Xamarin.android,Dotnet Httpclient,现在我正在Visual Studio 2017中进行Xamarin.Forms项目。 我正在尝试使用HttpClient上传图像,并通过php代码将文件发布到我的服务器目录。但是下面的代码仍然不起作用 我可以在我的应用程序上获取照片和显示,但无法上传到服务器 请帮忙 C#文件 异步任务GetPhoto(Func getPhotoFunc) { IsEnabled=false; 尝试 { var photo=wait getPhotoFunc(); 如果(照片==null) 返回; Image=n

现在我正在Visual Studio 2017中进行Xamarin.Forms项目。 我正在尝试使用HttpClient上传图像,并通过php代码将文件发布到我的服务器目录。但是下面的代码仍然不起作用

我可以在我的应用程序上获取照片和显示,但无法上传到服务器

请帮忙

C#文件

异步任务GetPhoto(Func getPhotoFunc) { IsEnabled=false; 尝试 { var photo=wait getPhotoFunc(); 如果(照片==null) 返回; Image=null; AllPredictions=新列表(); Image=SKBitmap.Decode(photo.GetStreamWithImageRotatedForExternalStorage()); 等待预报照片(照片); IsEnabled=true; 字节[]位图数据; var stream=newmemoryStream(); photo.GetStream().CopyTo(流); bitmapData=stream.ToArray(); var fileContent=新的ByteArrayContent(位图数据); fileContent.Headers.ContentType=MediaTypeHeaderValue.Parse(“应用程序/八位字节流”); fileContent.Headers.ContentDisposition=新的ContentDispositionHeaderValue(“表单数据”) { Name=“file”, FileName=“image\u test.jpg” }; 字符串边界=“-8393774HY373773”; MultipartFormDataContent multipartContent=新的MultipartFormDataContent(边界); multipartContent.Add(fileContent); HttpClientHandler clientHandler=新的HttpClientHandler(); HttpClient HttpClient=新的HttpClient(clientHandler); HttpResponseMessage响应=等待httpClient.PostAsync(“http://it2.sut.ac.th/project61_g23/php/upload-image.php“,多部分内容); response.EnsureSuccessStatusCode(); } 捕获(例外情况除外) { TrackError(例如,新字典{{“操作”,“获取预测”}); wait Application.Current.MainPage.DisplayAlert(“Error”,$”发生错误:{ex.Message},“OK”); } 最后 { 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>';
?>

我就是这样使用Xamarin表单和PHP的。在我的网站上查看代码

C#代码为

PHP代码是


HTML包含无效字符,该字符将出现在正在上载的二进制数据中。您需要使用convert.ToBase64String(字符串)将二进制文件转换为64位字符串。以下是对此的讨论。您可以参考。
<?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>';
?>
using Plugin.Media;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace UploadPicToServer
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}

private async void btnUpload_Clicked(object sender, EventArgs e)
{

if (!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
return;
}
var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,

});

if (file == null)
return;

string fileName = file.Path;
image.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});

//UploadImage1(file.AlbumPath);
UploadImage(file.GetStream(), fileName);
}
private async void UploadImage(Stream mfile, string fileName)
{
int authorID = 2;
string username = "yourusername";

var url = "https://yourwebsite.com/ba-add-profile-pic.php";
url += "?id="+ authorID +"&username="+ username; //any parameters you want to send to the php page.

try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://yourwebsite.com/");
MultipartFormDataContent form = new MultipartFormDataContent();
//HttpContent content = new StringContent("fileToUpload");
//form.Add(content, "fileToUpload");

var stream = mfile;
StreamContent content = new StreamContent(stream);

//get file's ext
string fileExt = fileName.Substring(fileName.Length - 4);
string fName = "User-Name-Here-123" + fileExt.ToLower();

content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileToUpload",
FileName = fName
};
form.Add(content);
var response = await client.PostAsync(url, form);
var result = response.Content.ReadAsStringAsync().Result;

}
catch (Exception e)
{
//debug
Debug.WriteLine("Exception Caught: " + e.ToString());

return;
}
}

public static byte[] ToArray(Stream s)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (!s.CanRead)
throw new ArgumentException("Stream cannot be read");

MemoryStream ms = s as MemoryStream;
if (ms != null)
return ms.ToArray();

long pos = s.CanSeek ? s.Position : 0L;
if (pos != 0L)
s.Seek(0, SeekOrigin.Begin);

byte[] result = new byte[s.Length];
s.Read(result, 0, result.Length);
if (s.CanSeek)
s.Seek(pos, SeekOrigin.Begin);
return result;
}
}
}
//parameters send in via querystring
if (!isset($_REQUEST['author']) || !isset($_REQUEST['username']) ) {
die('{"status" : "Bad", "reason" : "Invalid Access"}');
}

$userID = $_REQUEST['author'];
$isGood = false;
try{

$uploaddir = '../someFolderToStoreTheImage/';
$fileName = basename($_FILES['fileToUpload']['name']);
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);

//CHECK IF ITS AN IMAGE OR NOT
$allowed_types = array ('image/jpeg', 'image/png', 'image/bmp', 'image/gif' );
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$detected_type = finfo_file( $fileInfo, $_FILES['fileToUpload']['tmp_name'] );
if ( !in_array($detected_type, $allowed_types) ) {
die ( '{"status" : "Bad", "reason" : "Not a valid image"}' );
}
//

if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
//echo "File is valid, and was successfully uploaded.\n";
echo '{"status" : "Success", "reason" "'. $fileName .'"}';
$isGood = true;
} else {
//echo "Possible file upload attack!\n";
echo '{"status" : "Bad", "reason" : "Unable to Upload Profile Image"}';
}

}
catch(Exception $e) {
echo '{"status" : "Bad", "reason" : "'.$e->getMessage().'"}';
}