Home Menu

Menu



Programación y Desarrollo para Android Subforo exclusivo para temas de programación de software para PDAs y desarrollo de aplicaciones, interfaces, etc bajo Android


 
Herramientas
  #1  
Viejo 12/07/13, 17:27:25
Avatar de alfredo89aob
alfredo89aob alfredo89aob no está en línea
Usuario novato en la web
Mensajes: 4
 
Fecha de registro: jul 2013
Mensajes: 4
Tu operador: Movistar
Mencionado: 0 comentarios
Tagged: 0 hilos
Problema envío archivos a servidor

Estoy haciendo una aplicación cuya función es la de envíar archivos grandes a
un servidor que usa PHP.

Con ficheros pequeños funciona perfectamente, pero al intentar enviar ficheros
grandes, me aparece la siguiente excepción:

Código:
07-12 15:11:55.214: E/AndroidRuntime(13818): java.lang.OutOfMemoryError
07-12 15:11:55.214: E/AndroidRuntime(13818):     at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:216)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at org.apache.harmony.luni.internal.net.www.protocol.http.RetryableOutputStream.write(RetryableOutputStream.java:60)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at java.io.DataOutputStream.write(DataOutputStream.java:99)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at com.example.tweetnews.ServicioLogsErrores.doFileUpload(ServicioLogsErrores.java:188)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at com.example.tweetnews.ServicioLogsErrores.access$0(ServicioLogsErrores.java:138)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at com.example.tweetnews.ServicioLogsErrores$1.run(ServicioLogsErrores.java:131)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at java.util.Timer$TimerImpl.run(Timer.java:284)
El código que realiza la subida es:

Código:
private void doFileUpload() {

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String existingFileName = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/audioPrueba.mp3";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        String responseFromServer = "";
        String urlString = "http://XXX/upload.php";

        try {

            // ------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(
                    existingFileName));
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don't use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + existingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // close streams
            Log.e("Debug", "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        } catch (IOException ioe) {
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }

        // ------------------ read the SERVER RESPONSE
        try {

            inStream = new DataInputStream(conn.getInputStream());
            String str;

            while ((str = inStream.readLine()) != null) {

                Log.e("Debug", "Server Response " + str);

            }

            inStream.close();

        } catch (IOException ioex) {
            Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
    }
Supongo, que la solución es dividir el fichero de alguna manera, y enviarlo por
partes. Si alguien pudiera echarme una mano sobre como hacer esto, o alguna
otra alternativa que solucione el problema, le estaría muy agradecido.


Gracias,

Un saludo
Responder Con Cita


  #2  
Viejo 15/07/13, 12:43:29
Avatar de Arasthel
Arasthel Arasthel no está en línea
Cocinero veterano
Mensajes: 1,946
Compra y venta: (1)
 
Fecha de registro: jun 2009
Localización: Almería
Mensajes: 1,946
Modelo de smartphone: Nexus 5
Versión de ROM: DroidKang
Tu operador: Amena
Mencionado: 393 comentarios
Tagged: 1 hilos
Lo único que se me ocurre es que se lea una cantidad más pequeña que la que tienes puesta varias veces hasta que se llegue al final y que esos datos se manden cada vez como bytes en base 64 con el "número de paquete" que tiene y que luego el server PHP se encargue de ensamblarlos según le llegan. Bastante más complicado, pero bueno.

Como ejemplo: StackOverflow

Un saludo.
Responder Con Cita
  #3  
Viejo 15/07/13, 17:07:23
Avatar de Carlosdelachica
Carlosdelachica Carlosdelachica no está en línea
Miembro del foro
Mensajes: 97
 
Fecha de registro: may 2013
Mensajes: 97
Modelo de smartphone: Samsung Galaxy S III
Tu operador: Movistar
Mencionado: 0 comentarios
Tagged: 0 hilos
Cita:
Originalmente Escrito por alfredo89aob Ver Mensaje
Estoy haciendo una aplicación cuya función es la de envíar archivos grandes a
un servidor que usa PHP.

Con ficheros pequeños funciona perfectamente, pero al intentar enviar ficheros
grandes, me aparece la siguiente excepción:

Código:
07-12 15:11:55.214: E/AndroidRuntime(13818): java.lang.OutOfMemoryError
07-12 15:11:55.214: E/AndroidRuntime(13818):     at java.io.ByteArrayOutputStream.expand(ByteArrayOutputStream.java:91)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at java.io.ByteArrayOutputStream.write(ByteArrayOutputStream.java:216)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at org.apache.harmony.luni.internal.net.www.protocol.http.RetryableOutputStream.write(RetryableOutputStream.java:60)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at java.io.DataOutputStream.write(DataOutputStream.java:99)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at com.example.tweetnews.ServicioLogsErrores.doFileUpload(ServicioLogsErrores.java:188)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at com.example.tweetnews.ServicioLogsErrores.access$0(ServicioLogsErrores.java:138)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at com.example.tweetnews.ServicioLogsErrores$1.run(ServicioLogsErrores.java:131)
07-12 15:11:55.214: E/AndroidRuntime(13818):     at java.util.Timer$TimerImpl.run(Timer.java:284)
El código que realiza la subida es:

Código:
private void doFileUpload() {

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        DataInputStream inStream = null;
        String existingFileName = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/audioPrueba.mp3";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        String responseFromServer = "";
        String urlString = "http://XXX/upload.php";

        try {

            // ------------------ CLIENT REQUEST
            FileInputStream fileInputStream = new FileInputStream(new File(
                    existingFileName));
            // open a URL connection to the Servlet
            URL url = new URL(urlString);
            // Open a HTTP connection to the URL
            conn = (HttpURLConnection) url.openConnection();
            // Allow Inputs
            conn.setDoInput(true);
            // Allow Outputs
            conn.setDoOutput(true);
            // Don't use a cached copy.
            conn.setUseCaches(false);
            // Use a post method.
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "Keep-Alive");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            dos = new DataOutputStream(conn.getOutputStream());
            dos.writeBytes(twoHyphens + boundary + lineEnd);
            dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\""
                    + existingFileName + "\"" + lineEnd);
            dos.writeBytes(lineEnd);
            // create a buffer of maximum size
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            buffer = new byte[bufferSize];
            // read file and write it into form...
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            while (bytesRead > 0) {

                dos.write(buffer, 0, bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

            }

            // send multipart form data necesssary after file data...
            dos.writeBytes(lineEnd);
            dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
            // close streams
            Log.e("Debug", "File is written");
            fileInputStream.close();
            dos.flush();
            dos.close();

        } catch (MalformedURLException ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        } catch (IOException ioe) {
            Log.e("Debug", "error: " + ioe.getMessage(), ioe);
        }

        // ------------------ read the SERVER RESPONSE
        try {

            inStream = new DataInputStream(conn.getInputStream());
            String str;

            while ((str = inStream.readLine()) != null) {

                Log.e("Debug", "Server Response " + str);

            }

            inStream.close();

        } catch (IOException ioex) {
            Log.e("Debug", "error: " + ioex.getMessage(), ioex);
        }
    }
Supongo, que la solución es dividir el fichero de alguna manera, y enviarlo por
partes. Si alguien pudiera echarme una mano sobre como hacer esto, o alguna
otra alternativa que solucione el problema, le estaría muy agradecido.


Gracias,

Un saludo
Aparte de lo que ya te han comentado, también deberias de introducir la parte de tu código que descarga/sube de internet en un AsyncTask, ya que si no bloqueas el hilo de ejecución principal.

http://developer.android.com/referen...AsyncTask.html

(Supongo que no lo haces, aunque como no pones todo el código quizás me equivoque )
Responder Con Cita
Respuesta

Estás aquí
Regresar   HTCMania > Todo sobre Android > Programación y Desarrollo para Android

Herramientas

Reglas de Mensajes
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Las caritas están On
Código [IMG] está On
Código HTML está Off

Saltar a Foro



Hora actual: 02:37:58 (GMT +1)

Cookies
Powered by vBulletin™
Copyright © vBulletin Solutions, Inc. All rights reserved.
 
HTCMania: líderes desde el 2007