我将Android中的图像作为Base64格式的字符串文件发送到我的localhost服务器。我正在测试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上。我认为写作时有一些许可问题。但是,我设置了所有权限,但没有任何更改。
答案 0 :(得分:0)
解决了它。问题是一些权限问题。我还将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";
}
?>