我如何得到image_name和image_tmp_name从一个字节[]在PHP


How do I get the image_name and image_tmp_name from a byte [] in PHP?

我目前正在从我的前端发送一个字节[]到我的域和php代码。我要发送的字节数组名为"photo",它像System.Text.Encoding一样发送。use UTF8, application/json。我的目标是得到字节[]到一个图像,然后把它上传到我的domainfolder(已经存在),我需要得到image_name和image_tmp_name从字节[]为了做到这一点?我有点不确定我应该如何确切地让这个工作。

我现在有这个代码:

<?php 
$value = json_decode(file_get_contents('php://input'));
if(!empty($value)) {
print_r($value);
}
?>

使用这段代码,打印给我一个包含byte[]的巨大文本行。

我现在如何从这个字节[]获得image_name和image_tmp_name ?我的目标是将图像上传到我的domainmap(名为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;
}

解决方案如下:像这样改变你的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-body中发送那个数据目录。所以在php这边,你需要先设置php://inputjson_decode(),然后是图像字节的base64_decode()