我正在从我的前端向我的域和PHP代码发送一个byte []。我发送的字节数组名为" photo"它像System.Text.Encoding.UTF8一样发送," application / json"。我的目标是将byte []转换为图像,然后将其上传到我的域文件夹(已存在)我是否需要从该字节[]获取image_name和image_tmp_name才能执行此操作?我有点不确定我应该如何让它发挥作用。
我目前有这段代码:
<?php
$value = json_decode(file_get_contents('php://input'));
if(!empty($value)) {
print_r($value);
}
?>
使用此代码,print会给我一个包含byte []的大量文本。
我现在如何从此byte []中获取image_name和image_tmp_name?我的目标是将图像上传到我的域名映射(名为photoFolder,已经存在),代码如下所示:
$image_tmp_name = ""; //I currently do not have this value
$image_name = ""; //I currently do not have this value
if(move_uploaded_file($image_tmp_name, "photoFolder/$image_name")) {
echo "image successfully uploaded";
}
我如何发送:
static public async Task <bool> createPhotoThree (byte [] imgData)
{
var httpClientRequest = new HttpClient ();
var postData = new Dictionary <string, object> ();
postData.Add ("photo", imgData);
var jsonRequest = JsonConvert.SerializeObject(postData);
HttpContent content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json");
var result = await httpClientRequest.PostAsync("http://myadress.com/test.php", content);
var resultString = await result.Content.ReadAsStringAsync ();
return true;
}
答案 0 :(得分:1)
这是解决方案。像这样更改C#
方法:
static public async Task<bool> createPhotoThree(string imgName, byte[] imgData) {
var httpClientRequest = new HttpClient();
var postData = new Dictionary<string, object>();
postData.Add("photo_name", imgName);
postData.Add("photo_data", imgData);
var jsonRequest = JsonConvert.SerializeObject(postData);
HttpContent content = new StringContent(jsonRequest, System.Text.Encoding.UTF8, "application/json");
var result = await httpClientRequest.PostAsync("http://myadress.com/test.php", content);
var resultString = await result.Content.ReadAsStringAsync();
return true;
}
和你php
这样的代码:
$input = file_get_contents('php://input');
$value = json_decode($input, true);
if (!empty($value) && !empty($value['photo_data']) && !empty($value['photo_name'])) {
file_put_contents($value['photo_name'], base64_decode($value['photo_data']));
}
您看,当您致电JsonConvert.SerializeObject(postData)
时,您的byte[]
会成为base64编码的字符串。而你正在POST体内发送数据。因此,在php
方面,您需要先json_decode()
php://input
,然后base64_decode()
图像字节。