簡體   English   中英

如何從PHP中的字節[]獲得image_name和image_tmp_name?

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

我目前正在從前端向我的域和PHP代碼發送一個字節[]。 我要發送的字節數組稱為“照片”,它的發送方式類似於System.Text.Encoding.UTF8,即“ application / json”。 我的目標是將字節[]放入圖像中,然后將其上載到我的domainfolder(已經存在)中,我是否需要從該字節[]中獲得image_name和image_tmp_name才能執行此操作? 我不確定應該如何使它正常工作。

我目前有以下代碼:

<?php 

$value = json_decode(file_get_contents('php://input'));

if(!empty($value)) {

print_r($value);
}

?>

使用此代碼,打印結果會給我一行包含字節[]的巨大文本。

現在如何從此字節[]獲取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;

}

這是解決方案。 像這樣更改您的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()圖像的字節數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM