我正在上传图片并从我的服务器检索响应。以下是我的PHP代码
<?php
//Constants for database connection
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','root');
define('DB_NAME','simplifiedcoding');
//We will upload files to this folder
//So one thing don't forget, also create a folder named uploads inside your project folder i.e. MyApi folder
define('UPLOAD_PATH', 'uploads/');
//connecting to database
$conn = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die('Unable to connect');
//An array to display the response
$response = array();
//if the call is an api call
if(isset($_GET['apicall'])){
//switching the api call
switch($_GET['apicall']){
//if it is an upload call we will upload the image
case 'uploadpic':
//first confirming that we have the image and tags in the request parameter
if(isset($_FILES['pic']['name']) && isset($_POST['tags'])){
//uploading file and storing it to database as well
try{
move_uploaded_file($_FILES['pic']['tmp_name'], UPLOAD_PATH . $_FILES['pic']['name']);
$stmt = $conn->prepare("INSERT INTO images (image, tags) VALUES (?,?)");
$stmt->bind_param("ss", $_FILES['pic']['name'],$_POST['tags']);
if($stmt->execute()){
$response['error'] = false;
$response['message'] = 'File uploaded successfully';
}else{
throw new Exception("Could not upload file");
}
}catch(Exception $e){
$response['error'] = true;
$response['message'] = 'Could not upload file';
}
}else{
$response['error'] = true;
$response['message'] = "Required params not available";
}
break;
//in this call we will fetch all the images
case 'getpics':
//getting server ip for building image url
$server_ip = gethostbyname(gethostname());
//query to get images from database
$stmt = $conn->prepare("SELECT id, image, tags FROM images");
$stmt->execute();
$stmt->bind_result($id, $image, $tags);
$images = array();
//fetching all the images from database
//and pushing it to array
while($stmt->fetch()){
$temp = array();
$temp['id'] = $id;
$temp['image'] = 'http://' . $server_ip . '/MyApi/'. UPLOAD_PATH . $image;
$temp['tags'] = $tags;
array_push($images, $temp);
}
//pushing the array in response
$response['error'] = false;
$response['images'] = $images;
break;
default:
$response['error'] = true;
$response['message'] = 'Invalid api call';
}
}else{
header("HTTP/1.0 404 Not Found");
echo "<h1>404 Not Found</h1>";
echo "The page that you have requested could not be found.";
exit();
}
//displaying the response in json
header('Content-Type: application/json');
echo json_encode($response);
?>
我能够成功上传图像并查看mysql服务器中的条目。我尝试使用邮递员,我在检索图像时得到了正确的响应但是当我点击我的Android应用程序中的按钮来检索上传图像的响应时,我什么都没得到。 Foll是我的Android代码
public class MainActivity extends AppCompatActivity {
//ImageView to display image selected
ImageView imageView, imageView2;
//edittext for getting the tags input
EditText editTextTags;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initializing views
imageView = (ImageView) findViewById(R.id.imageView);
editTextTags = (EditText) findViewById(R.id.editTextTags);
imageView2 = findViewById(R.id.image2);
//checking the permission
//if the permission is not given we will open setting to add permission
//else app will not open
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
finish();
startActivity(intent);
return;
}
//adding click listener to button
findViewById(R.id.buttonUploadImage).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//if the tags edittext is empty
//we will throw input error
if (editTextTags.getText().toString().trim().isEmpty()) {
editTextTags.setError("Enter tags first");
editTextTags.requestFocus();
return;
}
//if everything is ok we will open image chooser
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, 100);
}
});
findViewById(R.id.retrieveimage).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "yy", Toast.LENGTH_SHORT).show();
StringRequest stringRequest=new StringRequest(Request.Method.GET,EndPoints.GET_PICS_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();
try {
JSONObject jsonObject=new JSONObject(response);
Log.i("Abbu", "onResponse: "+response.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this, "error", Toast.LENGTH_SHORT).show();
}
});
// Volley.newRequestQueue(getApplicationContext()).add(stringRequest);
MySingleton.getMySingleton(getApplicationContext()).addToRequestQueue(stringRequest);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
//getting the image Uri
Uri imageUri = data.getData();
try {
//getting bitmap object from uri
Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
//displaying selected image to imageview
imageView.setImageBitmap(bitmap);
//calling the method uploadBitmap to upload image
uploadBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* The method is taking Bitmap as an argument
* then it will return the byte[] array for the given bitmap
* and we will send this array to the server
* here we are using PNG Compression with 80% quality
* you can give quality between 0 to 100
* 0 means worse quality
* 100 means best quality
* */
public byte[] getFileDataFromDrawable(Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 80, byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
private void uploadBitmap(final Bitmap bitmap) {
//getting the tag from the edittext
final String tags = editTextTags.getText().toString().trim();
//our custom volley request
VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, EndPoints.UPLOAD_URL,
new Response.Listener<NetworkResponse>() {
@Override
public void onResponse(NetworkResponse response) {
try {
JSONObject obj = new JSONObject(new String(response.data));
Log.i("abu", "onResponse: " + obj);
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
/*
* If you want to add more parameters with the image
* you can do it here
* here we have only one parameter with the image
* which is tags
* */
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("tags", tags);
return params;
}
/*
* Here we are passing image by renaming it with a unique name
* */
@Override
protected Map<String, DataPart> getByteData() {
Map<String, DataPart> params = new HashMap<>();
long imagename = System.currentTimeMillis();
params.put("pic", new DataPart(imagename + ".png", getFileDataFromDrawable(bitmap)));
return params;
}
};
//adding the request to volley
Volley.newRequestQueue(this).add(volleyMultipartRequest);
}
}
当我点击我的检索按钮时没有任何反应。非常感谢任何帮助。