我想使用HttpClient将文件上传到php脚本,以将其保存在Windows Phone 8.1应用程序的服务器上。
这是我从this post获得的C#代码。
private async Task<string> GetRawDataFromServer(byte[] data)
{
//Debug.WriteLine("byte[] data length:" + Convert.ToBase64String(data).Length);
var requestContent = new MultipartFormDataContent();
// here you can specify boundary if you need---^
var imageContent = new ByteArrayContent(data);
imageContent.Headers.ContentType =
MediaTypeHeaderValue.Parse("image/jpeg");
requestContent.Add(imageContent, "image", "image.jpg");
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://www.x.net/");
var result = client.PostAsync("test/fileupload.php", requestContent).Result;
return result.Content.ReadAsStringAsync().Result;
}
}
使用此代码,我将检索php脚本中的数据
<?
function base64_to_image( $imageData, $outputfile ) {
/* encode & write data (binary) */
$ifp = fopen( $outputfile, "wb" );
fwrite( $ifp, base64_decode( $imageData ) );
fclose( $ifp );
/* return output filename */
return( $outputfile );
}
if (isset($_POST['image'])) {
base64_to_jpeg($_POST['image'], "image.jpg");
}
else
die("no image data found");
?>
但我总能得到的结果是&#34;没有找到数据&#34;虽然有一个图像文件。我是否做错了将其作为POST参数传递?
答案 0 :(得分:22)
好的经过几个小时的研究,我发现我应该从草稿中重新开始。 我使用以下C#代码模拟Html表单上传:
private async Task<string> UploadImage(StorageFile file)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://your.url.com/");
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new StringContent("fileToUpload");
form.Add(content, "fileToUpload");
var stream = await file.OpenStreamForReadAsync();
content = new StreamContent(stream);
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileToUpload",
FileName = file.Name
};
form.Add(content);
var response = await client.PostAsync("upload.php", form);
return response.Content.ReadAsStringAsync().Result;
}
我接收数据的php文件如下所示:
<?php
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);
echo '<pre>';
if (move_uploaded_file($_FILES['fileToUpload']['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);
?>
现在它可以正常工作,我希望有人可以重用我的代码。