duanchui1279 2018-10-10 10:48
浏览 50
已采纳

从Android上传图像到Web服务器

I am developing an Android application that allows user to upload images from their Android to the a 000webhost server, by referring to this link, I had managed to successfully send the image to the web server (file manager?).

However, I'd like to send the image to the database of the server instead, but I had been facing issue inserting the image into the database, below is the PHP code I am using:

<?php
include 'connection.php';

$con = mysqli_connect($hostname_localhost, $username_localhost, $password_localhost, $database_localhost);

if (mysqli_connect_error()){
    echo 'Error: Connection failed.';
    exit();
}

// Get image string posted from Android App
$base=$_REQUEST['image'];

// Get file name posted from Android App
$filename = $_REQUEST['filename'];

// Decode Image
$binary=base64_decode($base);
header('Content-Type: bitmap; charset=utf-8');

$sql = "INSERT INTO images (bitmap, name) VALUES ('$binary', '$filename')"; 
//mysqli_query($con, $sql)

if ($con->query($sql) === TRUE) {
    echo 'Success';
} else {
  //  Images will be saved under 'upload' folder
    $file = fopen('upload/'.$filename, 'wb');

//  Create File
    fwrite($file, $binary);
    fclose($file);
    echo 'Image upload complete, Please check your php file directory';
}
mysqli_close($con);
?>

My database named images has 3 columns:

id INT(100) AUTO_INCREMENT PRIMARY KEY
bitmap TEXT
name VARCHAR(100)

I tried passing just the filename into the database earlier and it worked, so I am suspecting the data type for bitmap is wrong.

Or should I, instead of passing the image into the database, keep the path of the image in the web server instead?

EDIT: I got rid of the if else statement and only saved the filename into the database, the image is saved to the server. For retrieval, I defined the path to the folder where images are being kept at, and used readfile() to send the image back to Android, using HTTPUrlConnection from here.

  • 写回答

1条回答 默认 最新

  • dtfbj24048 2018-10-10 13:08
    关注

    you can save the files in server and keep the filename in DB is the preferred solution. Also there is upload limit for every server. You can increase by editing server configuration or using php ini_set.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行