[英]Decode Base64 string in PHP recieved from JSON post
我正在一個項目中,我可以選擇一個圖像(選擇簡單文件)並將其通過JSON發送到PHP MySQL插入頁面。
上傳頁面如下所示:
if (input.files && input.files[0]) {
var FR = new FileReader();
FR.onload = function(e) {
$('#img').attr("src", e.target.result);
var Naam = $('input[type=file]').val();
$('#base').text(e.target.result);
var Foto = e.target.result;
var Barcode = $('#barcode').val();
obj['Barcode'] = Barcode;
obj['Naam'] = Naam;
obj['Foto'] = Foto;
//execute ajax send
$.ajax({
url : 'insert.php',
type : 'POST',
data : obj,
dataType : 'json',
success : function(msg) {
alert("msg");
}
});
//$.post("insert.php", obj, function (data) {}, "json");
//alert("msg");
};
FR.readAsDataURL(input.files[0]);
和我的PHP頁面:
$Barcode = $_POST["Barcode"];
$Naam = $_POST["Naam"];
$Name = preg_replace('/^.+[\\\\\\/]/', '', $Naam);
$Foto = base64_decode($_POST["Foto"]);
$query = "INSERT INTO voorraad_foto (barbody, location, foto) VALUES ('$Barcode','$Name','{$Foto}')";
$results = mysqli_query($db,$query);
我的表字段是BLOB。
但是,當它執行此操作時,一切正常,除了它不會將其插入為Blob而是純字符串
我已經嘗試過刪除
preg_replace('#data:image/[^;]+;base64,#', '', $Foto)
但沒有任何區別,嘗試添加標題時相同,但沒有任何區別。
我在做什么錯,還是我沒有得到明顯的幫助?
謝謝。
我以某種方式解決了它:
我編寫了一個獲取Base64字符串,對其進行解碼並將其寫入Temp文件的函數。 然后,我再次讀取該文件,並將其上傳到我的數據庫。 成功后,刪除文件。
這可能不是最有效的方法,但是可以!
function WriteToImageAndGetData($base64_string, $File) {
//Write to file
$ifp = fopen($File, "wb");
$data = explode(',', $base64_string); //Split Base64 string
fwrite($ifp, base64_decode($data[1])); //Decode Base64 string
fclose($ifp);
//Read from file
$fp = fopen($File, 'r');
$data = fread($fp, filesize($File)); //Read file contents
$data = addslashes($data);
fclose($fp);
return $data;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.