PHP – Android uses the volley library to upload images to the server

I want to use the volleyball library to upload my images from the camera to my 000webhost.com server

I want to find out what went wrong and suggest a complete code solution

I tried to write code, but it didn't work

I received the following error:

D/URL﹕ http:/plantNow.net16.net/uploaded.PHP
D/ERROR﹕ Error [com.android.volley.NoConnectionError: java.net.UnkNownHostException: 

My PHP uploaded.php looks like this. I want to destroy the image and image path in the server

<?PHP
 if ($_SERVER['REQUEST_METHOD'] == 'POST') {
     $image = $_POST['image'];
     require_once('dbconnect.PHP');
     $sql ="SELECT id FROM images ORDER BY id ASC";
     $res = MysqLi_query($con,$sql);
     $id = 0;

     while ($row = MysqLi_fetch_array($res)) {
         $id = $row['id'];
     }

     $path = "uploadedimages/$id.jpeg";
     $actualpath = "http://plantNow.net16.net/$path";
     $sql = "INSERT INTO images (image) VALUES ('$actualpath')";

    if (MysqLi_query($con,$sql)) {
        file_put_contents($path,base64_decode($image));
        echo "Successfully Uploaded";
    }

    MysqLi_close($con);
} else {
    echo "Error";
}
?>

My main activity is skydiving. The code is as follows:

public class MainActivity extends Activity {
ProgressDialog prgDialog;
String encodedString;
String fileName;
private static int RESULT_LOAD_IMG = 1;
private Button buttonUploadPhoto;
private ImageView myimage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    prgDialog = new ProgressDialog(this);
    // Set Cancelable as False
    prgDialog.setCancelable(false);

    buttonUploadPhoto = (Button) findViewById(R.id.uploadPhoto);
    myimage = (ImageView) findViewById(R.id.imgView);



    buttonUploadPhoto.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            uploadImage();

        }
    });

}

public void loadImagefromGallery(View view) {
    // Create intent to Open Image applications like Gallery, Google Photos
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    // Start the Intent
    startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}

// When Image is selected from Gallery
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        String fileNameSegments[] = picturePath.split("/");
        fileName = fileNameSegments[fileNameSegments.length - 1];

        Bitmap myImg = BitmapFactory.decodeFile(picturePath);
        myimage.setImageBitmap(myImg);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        // Must compress the Image to reduce image size to make upload easy
        myImg.compress(Bitmap.CompressFormat.PNG, 50, stream);
        byte[] byte_arr = stream.toByteArray();
        // Encode Image to String
        encodedString = Base64.encodeToString(byte_arr, 0);

        uploadImage();
    }
}



/**
 * API call for upload selected image from gallery to the server
 */
public void uploadImage() {

    RequestQueue rq = Volley.newRequestQueue(this);
    String url = "http:/plantNow.net16.net/uploaded.PHP";
    Log.d("URL", url);
    StringRequest stringRequest = new StringRequest(Request.Method.POST,
            url, new Response.Listener<String>() {

        @Override
        public void onResponse(String response) {
            try {
                Log.e("RESPONSE", response);
                JSONObject json = new JSONObject(response);

                Toast.makeText(getBaseContext(),
                        "The image is upload", Toast.LENGTH_SHORT)
                        .show();

            } catch (JSONException e) {
                Log.d("JSON Exception", e.toString());
                Toast.makeText(getBaseContext(),
                        "Error while loadin data!",
                        Toast.LENGTH_LONG).show();
            }

        }

    }, new Response.ErrorListener() {
        @Override
        public void one rrorResponse(VolleyError error) {
            Log.d("ERROR", "Error [" + error + "]");
            Toast.makeText(getBaseContext(),
                    "Cannot connect to server", Toast.LENGTH_LONG)
                    .show();
        }
    }) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();

            params.put("image", encodedString);
            params.put("filename", fileName);

            return params;

        }

    };
    rq.add(stringRequest);
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    // Dismiss the progress bar when application is closed
    if (prgDialog != null) {
        prgDialog.dismiss();
    }
}

This seems to me to be a typo

Try to change:

String url = "http:/plantNow.net16.net/uploaded.PHP"

To:

String url = "http://plantNow.net16.net/uploaded.PHP"

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>