How to capture camera image from your phone and send it to the server via Rest using Volley?

Asked

Viewed 527 times

3

I’m developing an application MOBILE that communicates with my web application, the application developed in Android Studio and the web on Playframework. I created a form on APK that already makes the consumption of the service via Rest using vólei, everything already working, however missing only send the image along with the other fields of the form. As I’m learning now to create and consume services, I’m having difficulty sending the image captured by the phone on the form. Can someone help me.

My Forms class in AS:

public class DenunciaActivity extends Activity implements AdapterView.OnItemSelectedListener, LocationListener {

double latitude = 0;
double longitude = 0;
public static final String TAG = "LOG";
//public static final String REGISTER_URL = "http://10.112.3.154:9000/Services/denuncia";
public static final String REGISTER_URL = "http://192.168.0.103:9000/Services/denuncia";
EditText femail, frua, fbairro, fcompl, fcidade, festado, fpais, fobs;
public String name;
public static final String KEY_USERNAME = "nome";
public static final String KEY_ADDRESS = "rua";
public static final String KEY_DISTRICT = "bairro";
public static final String KEY_COMPLEMENT = "complemento";
public static final String KEY_CITY = "cidade";
public static final String KEY_STATE = "estado";
public static final String KEY_NOTE = "observacao";
public static final String KEY_DATE = "data";
public static final String KEY_EMAIL = "email";
public static final String KEY_LAT = "latitude";
public static final String KEY_LONG = "longitude";
public static final String KEY_COUNTRIE = "pais";
public static final String KEY_STATUS = "status";
SimpleDateFormat formataData = new SimpleDateFormat("dd/MM/yyyy");
Date data = new Date();
String dataFormatada = formataData.format(data);
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_denuncia );
    FacebookSdk.sdkInitialize(this);
    readMyCurrentCoordinates();
    Bundle inBundle = getIntent().getExtras();
    name = inBundle.get("name").toString();
    frua = (EditText) findViewById(R.id.rua);
    fbairro = (EditText) findViewById(R.id.bairro);
    fcompl = (EditText) findViewById(R.id.complemento);
    fcidade = (EditText) findViewById(R.id.cidade);
    festado = (EditText) findViewById(R.id.estado);
    fpais = (EditText) findViewById(R.id.pais);
    fobs = (EditText) findViewById(R.id.observacao);
    femail = (EditText) findViewById(R.id.email);

        EditText nome = (EditText)findViewById(R.id.nome);
        nome.setText(name, TextView.BufferType.EDITABLE);
    Button enviar = (Button) findViewById( R.id.enviar );


    enviar.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(valid() == true){
                registerForms();
            }
        }
    } );


}
public void tirarFoto(View view){
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    startActivityForResult(intent, 0);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    if(data != null){
        Bundle bundle = data.getExtras();
        if(bundle != null){
            Bitmap img = (Bitmap) bundle.get("data");
            Toast toast = Toast.makeText(getApplicationContext(), "Foto anexada", Toast.LENGTH_LONG);
            toast.show();
        }
    }
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState( outState );
}

@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {}

@Override
public void onNothingSelected(AdapterView<?> parent) {}
public void registerForms() {

    final String address = frua.getText().toString().trim();
    final String district = fbairro.getText().toString().trim();
    final String city = fcidade.getText().toString().trim();
    final String email = femail.getText().toString().trim();
    final String complement = fcompl.getText().toString().trim();
    final String state = festado.getText().toString().trim();
    final String note = fobs.getText().toString().trim();
    final String countries = fpais.getText().toString().trim();


    StringRequest stringRequest = new StringRequest( Request.Method.POST, REGISTER_URL, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {

            if (response.contains("Erro")) {
                Toast.makeText( DenunciaActivity.this, response, Toast.LENGTH_LONG ).show();

            } else {
                Intent intent = new Intent(DenunciaActivity.this, MainActivity.class);
                Toast.makeText( DenunciaActivity.this, response, Toast.LENGTH_LONG ).show();
                startActivity(intent);
            }

        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText( DenunciaActivity.this, error.toString(), Toast.LENGTH_LONG ).show();
                    Log.i( TAG, "Lat: " + error );
                }
            } ) {
        @Override
        protected Map<String, String> getParams() {
            Map<String, String> map = new HashMap<String, String>();
            map.put( KEY_USERNAME, name );
            map.put( KEY_DATE, dataFormatada );
            map.put( KEY_STATE, state );
            map.put( KEY_CITY, city );
            map.put( KEY_DISTRICT, district );
            map.put( KEY_ADDRESS, address );
            map.put( KEY_EMAIL, email );
            map.put( KEY_COMPLEMENT, complement );
            map.put( KEY_COUNTRIE, countries );
            map.put( KEY_LAT, String.valueOf( latitude ) );
            map.put( KEY_LONG, String.valueOf( longitude ) );
            map.put( KEY_NOTE, note );
            map.put( KEY_STATUS, "ATIVO" );
            Log.i( TAG, "Lat: " + longitude +" "+latitude);
            return map;
        }

    };

    RequestQueue requestQueue = Volley.newRequestQueue( this );
    requestQueue.add( stringRequest );
}

}

On the other side, my service:

public class Services extends Controller {
public static void denuncia(@Valid String nome, String data, String rua, String bairro, String complemento, String cidade, String estado, String pais, String observacao, String email, String latitude, String longitude, Status status) {
    if (validation.hasErrors()) {
        String mensagem = "Erro ao cadastrar";
        JsonObject j = new JsonObject();
        j.addProperty("Erro", 404);
        j.addProperty("msg", mensagem);
        renderJSON(j);
    } else {
        String msgsucess = "Cadastrado com sucesso!";
        Denuncia denuncia = new Denuncia();
        denuncia.nome = nome;
        denuncia.data = data;
        denuncia.rua = rua;
        denuncia.bairro = bairro;
        denuncia.complemento = complemento;
        denuncia.cidade = cidade;
        denuncia.estado = estado;
        denuncia.pais = pais;
        denuncia.observacao = observacao;
        denuncia.email = email;
        denuncia.latitude = latitude;
        denuncia.longitude = longitude;
        denuncia.status = status;
        denuncia.save();
        JsonObject j = new JsonObject();
        j.addProperty("Success", 200);
        j.addProperty("msg", msgsucess);
        renderJSON(j);
    }
}
}
  • Do you want to send this image via form-data? or Base64?

  • Upload via Base64 @Lmaker

1 answer

2


It follows code that I use in one of my legacy applications, but it solves your problem. You will put it together in onActivityResult:

Bitmap img = (Bitmap)data.getExtras().get("data");

ByteArrayOutputStream stream = new ByteArrayOutputStream();
img.compress(Bitmap.CompressFormat.JPEG, 100, stream);
String foto = Base64.encodeToString(stream.toByteArray(), Base64.DEFAULT);

Just be careful about the size of the request, many web servers limit the size of the request.

  • Computer CDS, how does it look on my model? I put public String photo; and gave error Value Too long for column "FOTO VARCHAR(255)": "STRINGDECODE('/9j/4AQSkZJRgABAQAAQABAAAAAAD....

  • If you’re doing data persistence (which is what it looks like, it’s a database column, correct me if I’m wrong), you have to increase the column size, with a text type, no size. Or create a type blob in the database and convert from Base64 to byte[] and write to that column.

  • Or create a type blob in the database and convert from Base64 to byte[] and write to that column. Try to do this

  • CDS Informatica can help me here https://answall.com/questions/267116/erro-ao-salvar-imagem-jpeg-no-banco-comostring-base64/267119?noredirect=1#comment547624_267119 I’m still hooked

Browser other questions tagged

You are not signed in. Login or sign up in order to post.