Posting base64 image to php server in android

后端 未结 3 1609
清歌不尽
清歌不尽 2021-01-17 03:56

I am working on a module in which user can upload the image to the server. To achieve this, I have to change selected image into Base64. After conversion, I have to use Jso

相关标签:
3条回答
  • 2021-01-17 04:40

    Please assign encoded value to used params

         encodedString = Base64.encodeToString(b,Base64.DEFAULT);
          Log.e("LOOK", encodedString);
    
          new PostImage().execute(encodedString);
    
    0 讨论(0)
  • 2021-01-17 04:58

    Add httpmime-4.3.6.jar and httpcore-4.3.3.jar into your libs folder and add into build.gradle and sync it than after do this step;

    This variable You have to define;

     private static int RESULT_LOAD_IMAGE = 1;
    private static final int CAMERA_REQUEST = 1;
    public static final int MEDIA_TYPE_IMAGE = 1;
    
    private static final String TAG = MainActivity.class.getSimpleName();
     public static final String IMAGE_DIRECTORY_NAME = "Android File Upload";
    Uri mImageCaptureUri;
    private static final int PICK_IMAGE = 1;
     File sourceFile;
    ProgressDialog pDialog;
    ContentBody pic;
    Bitmap bitmap;
    

    than open gallary code.put into your Onclick.

    Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(i, RESULT_LOAD_IMAGE);
    

    this is OnActivityResult

     @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    
        if (requestCode == PICK_IMAGE && 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();
    
            decodeFile(picturePath);
            new ImageUploadTask().execute();
        }else {
    
            Toast.makeText(getApplicationContext(), "User Canceled",
                    Toast.LENGTH_LONG).show();
    
        }
    
    }
    

    after this

      public void decodeFile(String filePath) {
        // Decode image size
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, o);
    
        // The new size we want to scale to
        final int REQUIRED_SIZE = 1024;
    
        // Find the correct scale value. It should be the power of 2.
        int width_tmp = o.outWidth, height_tmp = o.outHeight;
        int scale = 1;
        while (true) {
            if (width_tmp < REQUIRED_SIZE && height_tmp < REQUIRED_SIZE)
                break;
            width_tmp /= 2;
            height_tmp /= 2;
            scale *= 2;
        }
    
        // Decode with inSampleSize
        BitmapFactory.Options o2 = new BitmapFactory.Options();
        o2.inSampleSize = scale;
        bitmap = BitmapFactory.decodeFile(filePath, o2);
        sourceFile = new File(filePath);
        Bitmap bmp = BitmapFactory.decodeFile(filePath);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 80, bos);
        InputStream in = new ByteArrayInputStream(bos.toByteArray());
        pic = new ByteArrayBody(bos.toByteArray(),"filename");
        loadimage.setImageBitmap(bitmap);
    }
    
    
    
    /**
     * The class connects with server and uploads the photo
     *
     *
     */
    class ImageUploadTask extends AsyncTask<Void, Void, String> {
    
    
        private String webAddressToPost;
    
        // private ProgressDialog dialog;
        private ProgressDialog dialog = new ProgressDialog(Tab1.this);
    
        @Override
        protected void onPreExecute() {
           dialog.setMessage("Uploading...");
           dialog.setCancelable(false);
            dialog.show();
    
        }
    
        @Override
        protected String doInBackground(Void... params) {
            try {
    
                // HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost("YOUR URL");
    
                MultipartEntity entity1 = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);
    
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);
                byte[] data = bos.toByteArray();
              //  String file = com.onepgr.samcom.apicalldemo2.Base64.encodeBytes(data);
                entity1.addPart("Parameter", pic);
    
                // entity.addPart("someOtherStringToSend", new StringBody("your string here"));
    
                httpPost.setEntity(entity1);
                HttpResponse response = httpclient.execute(httpPost, localContext);
                BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                String sResponse = reader.readLine();
                Log.d("------>>>>",sResponse);
                return sResponse;
            } catch (Exception e) {
                // something went wrong. connection with the server error
            }
            return null;
        }
    
        @Override
        protected void onPostExecute(String result) {
            dialog.dismiss();
            Toast.makeText(getApplicationContext(), "Profile picture change",
                    Toast.LENGTH_LONG).show();
    
        }
    
    }
    

    Don't forget to add httpmime-4.3.6.jar and httpcore-4.3.3.jar file into your project.

    0 讨论(0)
  • 2021-01-17 05:00

    I checked your error line at

    JSONObject json = jsonParser.makeHttpRequest(uri,"POST",params);
    

    but could not found makeHttpRequest this Method.so giving you below link, Make sure you get Success response and then you go for JSONObject parsing.

    Please check Link 1 Link2 download jar file Asynchronous Http Client and make Api call like

    public void makeHTTPCall() {
            prgDialog.setMessage("Invoking Php");       
            RequestParams params = new RequestParams();
            params.put("key", "value");
            params.put("more", "data");
            AsyncHttpClient client = new AsyncHttpClient();
            // Don't forget to change the IP address to your LAN address. Port no as well.
            client.post("http://192.168.2.5:9000/imgupload/upload_image.php",
                    params, new AsyncHttpResponseHandler() {
                        // When the response returned by REST has Http
                        // response code '200'
                        @Override
                        public void onSuccess(String response) {
                            // Hide Progress Dialog
                            prgDialog.hide();
                            Toast.makeText(getApplicationContext(), response,
                                    Toast.LENGTH_LONG).show();
                        }
    
                        // When the response returned by REST has Http
                        // response code other than '200' such as '404',
                        // '500' or '403' etc
                        @Override
                        public void onFailure(int statusCode, Throwable error,
                                String content) {
                            // Hide Progress Dialog
                            prgDialog.hide();
                            // When Http response code is '404'
                            if (statusCode == 404) {
                                Toast.makeText(getApplicationContext(),
                                        "Requested resource not found",
                                        Toast.LENGTH_LONG).show();
                            }
                            // When Http response code is '500'
                            else if (statusCode == 500) {
                                Toast.makeText(getApplicationContext(),
                                        "Something went wrong at server end",
                                        Toast.LENGTH_LONG).show();
                            }
                            // When Http response code other than 404, 500
                            else {
                                Toast.makeText(
                                        getApplicationContext(),
                                        "Error Occured \n Most Common Error: \n1. Device not connected to Internet\n2. Web App is not deployed in App server\n3. App server is not running\n HTTP Status code : "
                                                + statusCode, Toast.LENGTH_LONG)
                                        .show();
                            }
                        }
                    });
        }
    
    0 讨论(0)
提交回复
热议问题