gpt4 book ai didi

php - 在 PHP 中接收 base64 编码的图像字符串并写入文件

转载 作者:行者123 更新时间:2023-12-04 18:54:28 25 4
gpt4 key购买 nike

我正在将图像作为 Base64 格式字符串文件从 Android 发送到我的本地主机服务器。我正在使用 Google Chrome Postman 扩展进行测试。

这是我的代码:

<?php
header('Content-type : bitmap; charset=utf-8');

if(isset($_POST["encoded_string"])){

$encoded_string = $_POST["encoded_string"];
$image_name = $_POST["image_name"];

$decoded_string = base64_decode($encoded_string);

$path = 'android_connect/images/'.$image_name;

$file = fopen($path, 'wb');

$is_written = fwrite($file, $decoded_string);
fclose($file);

if($is_written > 0) {

$connection = mysqli_connect('localhost', 'root', 'rifat20081995','phpmyadmin');
$query = "INSERT INTO Pictures(Name,Path) values('$image_name','$path');";

$result = mysqli_query($connection, $query) ;

if($result){
echo "success";
}else{
echo "failed";
}

mysqli_close($connection);
}
else
{
echo "file not written";
}
}
?>

我看到很多例子都使用了这样的代码,但对我来说,它每次都说“文件未写入”。

我在 Ubuntu 上。我认为写作时存在一些权限问题。但是,我设置了所有权限,但没有任何改变。

最佳答案

解决了。问题是一些权限问题。我也替换了fwrite()file_put_contents($dir . '/' . $image_name, $decoded_string) .

完整代码:

<?php
header('Content-type : bitmap; charset=utf-8');

if(isset($_POST["encoded_string"])){


$dir = 'images';
if( !file_exists($dir) )
{
$oldmask = umask(0);// helpful when used in linux server
mkdir ($dir, 0744);
}

$encoded_string = $_POST["encoded_string"];
$image_name = $_POST["image_name"];
$decoded_string = base64_decode($encoded_string);

file_put_contents ($dir.'/'.$image_name, $decoded_string);
$path=$dir.'/'.$image_name;

$connection = mysqli_connect('localhost', 'root', 'rifat20081995','phpmyadmin');
$query = "INSERT INTO Pictures(Name,Path) values('$image_name','$path');";

$result = mysqli_query($connection, $query) ;

if($result){
echo "success";
}else{
echo "failed";
}

mysqli_close($connection);
}
else
{
echo "file not written";
}

?>

关于php - 在 PHP 中接收 base64 编码的图像字符串并写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40271495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com