到目前為止,我正在傳遞單個 base64 字串,但現在我需要傳遞多個 base64 字串并通過 PHP 腳本發送到服務器。
截至目前,我的代碼僅發送單個資料
$imagebase64 //it contains base64 array like -['data:image/jpeg;base64,/9j/4A','data:image/jpeg;base64,/9j/4A']
$("#downloadAll").click(function () {
$.ajax({
type: "POST",
url: "imageUpload.php",
data: {
// Sending single as of now
base64Img: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD…1jSchh2MkeFK5Anv7fbTv5SKFqOFdOvm764mRVLQgtO8RoP/Z",
},
contentType: "application/octet-stream",
error: function (err) {
console.log("There was an error. Try again please!", err);
},
success: function (msg) {
console.log(msg);
},
});
});
PHP 腳本
$base64string = $_POST['data'];
$uploadpath = 'image-cropper';
$parts = explode(";base64,", $base64string);
$imageparts = explode("image/", @$parts[0]);
$imagetype = $imageparts[1];
$imagebase64 = base64_decode($parts[1]);
$file = $uploadpath . uniqid() . '.jpeg';
file_put_contents($file, $imagebase64);
按照建議更新代碼后-
注意:未定義的索引:第 1 行 /var/www/html/image-cropper/imageUpload.php 中的資料和空
array()發布到upload.php
阿賈克斯呼叫:
$("#downloadAll").click(function () {
var imagebase64 = "<?= $imagebase64 ?>";
$.ajax({
type: "POST",
url: "imageUpload.php",
data: { imagesBase64: JSON.stringify(imagesBase64) },
contentType: "application/json; charset=utf-8",
error: function (err) {
console.log("There was an error. Try again please!", err);
},
success: function (msg) {
console.log(msg);
},
});
});
PHP:
$base64string = $_POST['data'];
$uploadpath = 'image-cropper';
$parts = explode(";base64,", $base64string);
$imageparts = explode("image/", @$parts[0]);
$imagetype = $imageparts[1];
$imagebase64 = base64_decode($parts[1]);
$file = $uploadpath . uniqid() . '.jpeg';
file_put_contents($file, $imagebase64);
uj5u.com熱心網友回復:
正如我對您的第一個代碼所了解的那樣 - 您的陣列具有已經在字串中的 base64 資料,因此無需再次轉換它。
$("#downloadAll").click(function () {
$.ajax({
type: "POST",
url: "imageUpload.php",
data: { data: imagesBase64 },
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" data, err);
},
success: function (data) {
console.log(data);
},
});
});
正如我看到你的 PHP 腳本有很多問題,它只用于處理單個專案,你也需要遍歷陣列。
$data = ($_POST['data']);
foreach($data as $base64_string ){
$filename_path = md5(time().uniqid()).".jpeg"; //use png or jpg if required
$base64_string = str_replace('data:image/jpeg;base64,', '', $base64_string);
$base64_string = str_replace(' ', ' ', $base64_string);
$decoded = base64_decode($base64_string);
//defining path
file_put_contents("image-cropper".$filename_path,$decoded);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441730.html
