我必须将应用程序中的图像发送到PHP服务器以及一些细节。 我写了下面的代码来发送详细信息,但不知道如何发送图像。有人可以帮我这个吗?
如您所见,我正在使用Map将数据发送到服务器。但是如何在此添加图像。任何帮助都会有所帮助。
StringRequest strReq = new StringRequest(Request.Method.POST, "URL",
new Response.Listener<String>() {
@Override
public void onResponse(String response)
{
Toast.makeText(getApplicationContext(), "Response", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(),"Response", Toast.LENGTH_LONG).show();
}
})
{
@Override
protected Map<String, String> getParams() {
Map<String, String> details = new HashMap<>();
details.put("id", session.getKey());
details.put("name", name.toString());
return details;
}
};
strReq.setShouldCache(false);
AppController.getInstance().addToRequestQueue(strReq);
答案 0 :(得分:0)
您必须将Image转换为String。喜欢这个
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;
}
然后你可以像这样添加图像
/ //Converting Bitmap to String
String image = getStringImage(bitmap);
params.put(KEY_IMAGE, image);
答案 1 :(得分:0)
private void uploadImage(final String id, final String name){
String tag_string_req = "req_upImage";
// pDialog.setMessage("Uploading image......");
// showDialog();
//converting image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
myBitmap.compress(Bitmap.CompressFormat.JPEG, 40, baos);
byte[] imageBytes = baos.toByteArray();
long imgSize = imageBytes.length;
final String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT);
// Log.d(TAG, "Image:" + imageString);
StringRequest strReq = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Response:" + String.valueOf(response));
//hideDialog();
try {
JSONObject jObj = new JSONObject(response);
int success = jObj.getInt("success");
if (success == 1) {
Toast.makeText(getApplicationContext(), "Image uploaded successfully", Toast.LENGTH_LONG).show();
} else {
// Error occurred in uploading. Get the error
// message
Toast.makeText(getApplicationContext(), "Some error occurred!. Try again ", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Uploading Error: " + error.getMessage());
// Toast.makeText(getApplicationContext(),error.getMessage(), Toast.LENGTH_LONG).show();
if (error instanceof TimeoutError || error instanceof NoConnectionError) {
Toast.makeText(getApplicationContext(), "Communication Error!.", Toast.LENGTH_LONG).show();
} else if (error instanceof AuthFailureError) {
Toast.makeText(getApplicationContext(), "Authentication Error!", Toast.LENGTH_SHORT).show();
} else if (error instanceof ServerError) {
Toast.makeText(getApplicationContext(), "Internal Server Error!", Toast.LENGTH_SHORT).show();
} else if (error instanceof NetworkError) {
Toast.makeText(getApplicationContext(), "Network Error!.", Toast.LENGTH_SHORT).show();
} else if (error instanceof ParseError) {
Toast.makeText(getApplicationContext(), "Parse Error!", Toast.LENGTH_SHORT).show();
}
hideDialog();
}
}) {
@Override
protected Map<String, String> getParams() {
// Posting params
Map<String, String> params = new HashMap<String, String>();
params.put("image", imageString);
params.put("name", name);
params.put("id", id);
return params;
}
};
// disabling volley retry policy
strReq.setRetryPolicy(new DefaultRetryPolicy(
0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}
php code
<?php
require_once 'db_config.php';
if($_SERVER['REQUEST_METHOD']=='POST')
{
$con = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
$sql ="SELECT image_id FROM table_images ORDER BY image_id ASC";
$res = mysqli_query($con,$sql);
$image_id = 0;
while($row = mysqli_fetch_array($res)){
$image_id = $row['image_id'];
}
// saving image in a folder
$path = "../uploads/images/$image_id.png";
$actualpath = "http://............./$path";
$response = array();
// check for required fields
if (isset($_POST['name']) && isset($_POST['image']) && isset($_POST['id']))
{
$name = $_POST['name'];
$image_id = $_POST['id'];
require_once 'db_Connect.php';
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO table_images(name, image, rest_id) VALUES('$name', '$actualpath', '$image_id')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Image successfully Uploaded.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
require_once 'db_config.php';
require_once 'db_Connect.php';
if(mysqli_query($con,$sql)){
$image = $_POST['image'];
file_put_contents($path,base64_decode($image));
/*echo "Successfully Uploaded";*/
}
mysqli_close($con);
}else{
echo "Error";
}
?>