我正在尝试从图片库(在 WP7 上)上传图片并将其保存在服务器上的文件夹中。
在服务器上,我使用 PHP 通过 POST 方法接收文件。
PHP 代码是:
<?php
$uploads_dir = 'files/'; //Directory to save the file that comes from client application.
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
?>
我已经尝试过一些方法,但它们似乎都失败了。
我已经使用 Client.UploadFile 方法在 Windows 窗体应用程序中完成了这项工作,但它似乎不能在 Windows Phone 应用程序上使用。
我认为 httpwebrequest 可以提供帮助,对吧?
到目前为止,这是我的 C# 代码:
public partial class SamplePage : PhoneApplicationPage
{
public SamplePage()
{
InitializeComponent();
}
PhotoChooserTask selectphoto = null;
private void SampleBtn_Click(object sender, RoutedEventArgs e)
{
selectphoto = new PhotoChooserTask();
selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
selectphoto.Show();
}
void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BinaryReader reader = new BinaryReader(e.ChosenPhoto);
image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
txtBX.Text = e.OriginalFileName;
}
}
}
我在某处读到图像需要转换为字节字符串,我不确定。
但是,请帮助我。
预先非常感谢。
我会将图像转换为 base64(请参阅 System.Convert),然后通过 POST 传输:
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://mydomain.cc/saveimage.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string postData = String.Format("image={0}", myBase64EncodedImage);
// Getting the request stream.
request.BeginGetRequestStream
(result =>
{
// Sending the request.
using (var requestStream = request.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(postData);
writer.Flush();
}
}
// Getting the response.
request.BeginGetResponse(responseResult =>
{
var webResponse = request.EndGetResponse(responseResult);
using (var responseStream = webResponse.GetResponseStream())
{
using (var streamReader = new StreamReader(responseStream))
{
string srresult = streamReader.ReadToEnd();
}
}
}, null);
}, null);
}
saveimage.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'], "my_path_to_store_images.jpg");
}
else
die("no image data found");
?>
注意:我没有测试过代码。可能存在拼写错误或其他错误。这只是为了说明我如何使用 POST 传输图像。
编辑作为对您评论的回复:我手头没有编码为 Base64 的代码,但以下是在 C# 中解码 Base64 编码图像的方法:
byte[] image = Convert.FromBase64String(str);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)