vendredi 29 mai 2015

Android- Upload photo to the server

*The UploadProduct.class register a product in my database and upload the photo to my server. I am trying to upload a file to my server. When I execute my app this work perfectly, the product is registered in the database but in my server , the photo had not been loaded.

When I debug , I put a breakpoint in httppost.setEntity(mpEntity); , the value of file atribute is /storage/emulated/0/Needyt/20150529_104715.jpg

The path where I save my files is http://ift.tt/1KCisaP and the path of upload.php is http://aaaa.com/app

Here my code:

atributes:

private List<NameValuePair> params = new ArrayList<NameValuePair>(1);
private File file;
private String imageFileName = "";
private String urlImag ="http://ift.tt/1KCisaP";
private EditText  etNombreProducto,etDescripcion,etPrecioDia,etPrecioSemana;
private Bitmap bitmap=null;

methods:

public void takePhoto() {



        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        imageFileName = timeStamp  + ".jpg";


        //Creamos el Intent para llamar a la Camara
        Intent cameraIntent = new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        //Creamos una carpeta en la memeria del terminal
        File imagesFolder = new File(
                Environment.getExternalStorageDirectory(), "Needyt");
        imagesFolder.mkdirs();
        //anadimos el nombre de la imagen
        file= new File(imagesFolder, imageFileName);
        Uri uriSavedImage = Uri.fromFile(file);
        //Le decimos al Intent que queremos grabar la imagen
        cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
        //Lanzamos la aplicacion de la camara con retorno (forResult)
        startActivityForResult(cameraIntent, 1);


    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //Comprovamos que la foto se a realizado
        if (requestCode == 1 && resultCode == RESULT_OK) {
            //Creamos un bitmap con la imagen recientemente
            //almacenada en la memoria
            bitmap= BitmapFactory.decodeFile(
                    Environment.getExternalStorageDirectory() +
                            "/aaaa/" + imageFileName);
//            //Anadimos el bitmap al imageView para
//            //mostrarlo por pantalla
//            img.setImageBitmap(bMap);
        }
    }


    private boolean uploadFoto(String imag){
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost httppost = new HttpPost("http://ift.tt/1Ruep13");
        MultipartEntity mpEntity = new MultipartEntity( );

        ContentBody contentBody = new FileBody(file,"image/jpeg");
        mpEntity.addPart("foto", contentBody);
        httppost.setEntity(mpEntity);
        try {
            httpclient.execute(httppost);
            httpclient.getConnectionManager().shutdown();
            return true;
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
    private boolean onInsert(){
        String nombreP = etNombreProducto.getText().toString();
        String descripcion = etDescripcion.getText().toString();
        String precioD = etPrecioDia.getText().toString();
        String precioS=etPrecioSemana.getText().toString();
        HttpClient httpclient;

        params.add(new BasicNameValuePair("nombre", nombreP));
        params.add(new BasicNameValuePair("descripcion", descripcion));
        params.add(new BasicNameValuePair("preciodia", precioD));
        params.add(new BasicNameValuePair("preciosemana", precioS));
        params.add(new BasicNameValuePair("imagen", urlImag + imageFileName));
        HttpPost httppost;
        httpclient=new DefaultHttpClient();
        httppost= new HttpPost("http://ift.tt/1KCisaR");
        // Url del Servidor

        try {
            httppost.setEntity(new UrlEncodedFormEntity(params));
            httpclient.execute(httppost);
            return true;
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return false;
    }

    private void serverUpdate(){
        if (file.exists())
            new ServerUpdate().execute();
        else
            Toast.makeText(UploadProduct.this, "Debes de hacer una foto",
                    Toast.LENGTH_LONG).show();

    }

    class ServerUpdate extends AsyncTask<String,String,String> {

        ProgressDialog pDialog;
        @Override
        protected String doInBackground(String... arg0) {
            Boolean b=uploadFoto(imageFileName);
            if(onInsert()&& b)
                runOnUiThread(new Runnable(){
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        Toast.makeText(UploadProduct.this, "Exito al subir la imagen",
                                Toast.LENGTH_LONG).show();
                    }
                });
            else
                runOnUiThread(new Runnable(){
                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        Toast.makeText(UploadProduct.this, "Sin exito al subir la imagen",
                                Toast.LENGTH_LONG).show();
                    }
                });
            return null;
        }
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(UploadProduct.this);
            pDialog.setMessage("Actualizando Servidor, espere..." );
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.show();
        }
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            pDialog.dismiss();
        }

    }

my upload.php

<?php

    $ruta = "app/imagenes/" .basename($_FILES['foto']['name']);
    if(move_uploaded_file($_FILES['foto']['tmp_name'], $ruta)){
            echo "success";
        } else{
            echo "fail";
        }
    ?>

Aucun commentaire:

Enregistrer un commentaire