Search code examples
javalaravellumencloudinary

How to upload an image file through android to cloudinary using lumen


I wrote some code in Lumen to upload images to cloudinary, the code works while testing using postman.

Right now i'm trying to upload the image via an android app rather than via postman, but that doesn't work for some reason.

Below is the image upload code from my Lumen app

    $image_name = $request->file('picture')->getRealPath();
    
    $cloudder = Cloudder::upload($image_name, null, [
        'folder' => '/dog-lovers',
        'discard_original_filename' => true,
    ]);
    $uploadResult = $cloudder->getResult();
    $file_url = $uploadResult["url"];
    
    $input = $request->all();
    $input['picture'] = $file_url;
    $ad = Ad::create($input);
    return array('error'=>false, 'message'=>'ad created successfully', 'data'=>$ad);

The above code works perfectly while testing on postman.

I then wrote some android code to pass the image from my phone to Lumen

    uploadImage.setOnClickListener(v -> {
        Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
        getIntent.setType("image/*");

        Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        pickIntent.setType("image/*");

        Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] {pickIntent});

        startActivityForResult(chooserIntent, PICK_IMAGE);
    });

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImageUri = data.getData();
        picturePath = getPath(getApplicationContext(), selectedImageUri);
        Log.i("UploadAdActivity", picturePath);
        Toast.makeText(this,picturePath, Toast.LENGTH_LONG).show();
    }
}

public static String getPath(Context context, Uri uri ) {
    String result = null;
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.getContentResolver( ).query( uri, proj, null, null, null );
    if(cursor != null){
        if ( cursor.moveToFirst( ) ) {
            int column_index = cursor.getColumnIndexOrThrow( proj[0] );
            result = cursor.getString( column_index );
        }
        cursor.close( );
    }
    if(result == null) {
        result = "Not found";
    }
    return result;
}

protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<>();
                params.put("picture", picturePath);
                return params;
            }

The above code doesn't work as the lumen app isn't able to get the image using the path provided, I've obviously made a mistake somewhere, but I don't know what it is nor how to fix it.

It would be really helpful if someone could explain what to do/ point out what i'm doing wrong


Solution

  • Well this might come in handy to someone, I was doing a few things wrong

    1. I was using a Volley String Request instead of a Volley Multipart request

      VolleyMultipartRequest multipartRequest = new VolleyMultipartRequest(Request.Method.POST, URLs.URL_UPLOAD_AD,
      
    2. you need to pass the picture/file using ByteData

      @Override
              protected Map<String, VolleyMultipartRequest.DataPart> getByteData() {
                  Map<String, VolleyMultipartRequest.DataPart> params = new HashMap<>();
      
                  long imageName = System.currentTimeMillis();
                  params.put("picture", new DataPart(imageName + ".png", getFileDataFromDrawable(bitmap))); mCoverImage.getDrawable()), "image/jpeg"));
      
                  return params;
              }
      
    3. You need to set the Headers using

      @Override
                  public Map<String, String> getHeaders() throws AuthFailureError {
                      HashMap<String, String> headers = new HashMap<String, String>();
                      return headers;
                  }