我创建了一个PHP脚本,允许我在MySQL数据库中保存来自HTML页面(表单POST)的图像,它做得很好,我可以看到表格中的行,也可以在浏览器中显示它们使用另一个名为 load_image_from_db.php 的PHP脚本。但是,当通过Android应用程序保存图像时,存在一些问题。
我可以使用android应用程序将图像上传到MySQL数据库,保存图像,我可以在PHPmyAdmin的表格中看到它们,但是当我尝试使用相同的PHP脚本显示它们时 load_image_from_db.php 它们不会显示(显示一个小的矩形矩形)。
我发现当我通过Form.html保存图像时需要32Kio,当我通过Android应用程序保存相同的图像时,它需要phpMyAdmin中的105 Kio(所有图像大约为* 3。
我将用于保存图像的java代码发布到MySQL DB中:
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
@Override
protected String doInBackground(Bitmap... params) {
RequestHandler rh = new RequestHandler();
Bitmap bitmap = params[0];
String uploadImage = getStringImage(bitmap);
HashMap<String, String> data = new HashMap<>();
data.put(UPLOAD_KEY, uploadImage);
String result = rh.sendPostRequest(UPLOAD_URL, data);
return result;
}
}
UploadImage ui = new UploadImage();
ui.execute(bitmap);
RequestHandler类:
public String sendPostRequest(String requestURL,
HashMap<String, String> postDataParams) {
URL url;
String response = "";
try {
url = new URL(requestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
response = br.readLine();
} else {
response = "Error Registering";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for (Map.Entry<String, String> entry : params.entrySet()) {
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
upload_image.php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$con = mysqli_connect("localhost","root","","othmane");
$image = $_POST['image'];
$sql = "INSERT INTO images (image) VALUES (?)";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"s",$image);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check == 1){
echo "Image Uploaded Successfully";
}else{
echo "Error Uploading Image";
}
mysqli_close($con);
}else{
echo "Error";
}
?>