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.

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

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记