Carga de matriz de bytes de imagen con httpurlconnection y android
Estoy desarrollando la pequeña aplicación Android en la que quería cargar la imagen de mi dispositivo Android a mi servidor. Estoy usando HttpURLConnection
para eso.
Lo hago de la siguiente manera:
- Obtener icono de la aplicación predeterminada que abre un archivo
- Abrir automáticamente el selector de intenciones para el archivo Android
- ¿Cómo puedo obtener el tipo mime de un archivo con su Uri?
- Evitar la caída de arrastre del tipo mime personalizado a EditText
- Android: el tipo mime para el anexo de correo electrónico no está configurado
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_down_float); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.JPEG, 100, bos); byte[] data = bos.toByteArray(); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "image/jpeg"); connection.setRequestMethod(method.toString()); ByteArrayOutputStream bout = new ByteArrayOutputStream(); bout.write(data); bout.close();
Estoy utilizando ByteArrayOutputStream
pero no sé cómo pasar esos datos con mi httpurlconnection. ¿Es esta la forma correcta de pasar datos de imagen sin procesar. Sólo quería enviar matriz de bytes que contiene datos de imagen. Sin conversión o sin envío de varias partes. Mi código funciona bien sin ningún error, pero mi servidor me da la respuesta {"error":"Mimetype not supported: inode\/x-empty"}
Hice esto con httpclient usando setEntity
y su funcionamiento muy bien con eso. Pero quiero usar urlconnection.
¿Estoy haciendo algo mal? ¿Como hacer esto? Gracias.
- MimeType derecho para abrir el archivo
- ¿Cómo calcula Android el tipo MIME de un URI para un intento implícito?
- ¿Tipo Mime para archivos .txt?
- Cómo abrir MIME - "application / x-509-server-cert" tipo en Android Moto G?
- ¿Existe una forma estándar de suscribirse a un feed mediante una aplicación de podcast?
- Cómo saber si el archivo .3gp es de audio o video en android
- ¿Cómo comprobar si una intención puede ser manejada de alguna actividad?
- Adjunto de Gmail y extensión personalizada
Debe abrir la conexión de flujo de salida y escribir los datos en ella. Usted podría intentar esto:
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.arrow_down_float); connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "image/jpeg"); connection.setRequestMethod(method.toString()); OutputStream outputStream = connection.getOutputStream(); ByteArrayOutputStream bos = new ByteArrayOutputStream(outputStream); bitmap.compress(CompressFormat.JPEG, 100, bos); bout.close(); outputStream.close();
Con esta declaración:
bitmap.compress(CompressFormat.JPEG, 100, bos);
Estás haciendo dos cosas: comprima el mapa de bits y envíe los datos obtenidos (los bytes que construyen el jpg) al flujo de bos, que envían los datos resultantes a la conexión de flujo de salida.
También puede escribir los datos en el flujo de salida de la conexión directamente, reemplazando esto:
ByteArrayOutputStream bos = new ByteArrayOutputStream(outputStream); bitmap.compress(CompressFormat.JPEG, 100, bos);
Con este:
bitmap.compress(CompressFormat.JPEG, 100, outputStream);
Espero que esto ayude a entender cómo funciona HttpUrlConnection.
Además, no debe cargar todo el mapa de bits por completo para evitar las excepciones "fuera de la memoria", abriendo el mapa de bits con los flujos, por ejemplo.
private void doFileUpload(){ HttpURLConnection conn = null; DataOutputStream dos = null; DataInputStream inStream = null; String exsistingFileName = "/sdcard/six.3gp"; // Is this the place are you doing something wrong. String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1*1024*1024; String urlString = "http://192.168.1.5/upload.php"; try { Log.e("MediaPlayer","Inside second Method"); FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) ); URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); 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=\"" + exsistingFileName +"\"" + lineEnd); dos.writeBytes(lineEnd); Log.e("MediaPlayer","Headers are written"); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; 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); } dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); BufferedReader in = new BufferedReader( new InputStreamReader( conn.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) tv.append(inputLine); // close streams Log.e("MediaPlayer","File is written"); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { Log.e("MediaPlayer", "error: " + ex.getMessage(), ex); } catch (IOException ioe) { Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe); } //------------------ read the SERVER RESPONSE try { inStream = new DataInputStream ( conn.getInputStream() ); String str; while (( str = inStream.readLine()) != null) { Log.e("MediaPlayer","Server Response"+str); } /*while((str = inStream.readLine()) !=null ){ }*/ inStream.close(); } catch (IOException ioex){ Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex); } }
Demostración completa
HttpParams httpParameters = new BasicHttpParams(); HttpProtocolParams.setContentCharset(httpParameters, HTTP.UTF_8); HttpProtocolParams.setHttpElementCharset(httpParameters, HTTP.UTF_8); HttpClient httpclient = new DefaultHttpClient(httpParameters); HttpPost httppost = new HttpPost(ServerConstants.urll); httppost.setHeader("Content-type","application/octet-stream");//application/octet-stream // the below is the important one, notice no multipart here just the raw image data httppost.setEntity(new ByteArrayEntity(imagebytess)); try { HttpResponse res = httpclient.execute(httppost); BufferedReader reader = new BufferedReader(new InputStreamReader( res.getEntity().getContent(), "UTF-8")); String sResponse; StringBuilder s = new StringBuilder(); System.out.println("Response: " + res.getStatusLine().getStatusCode()); while ((sResponse = reader.readLine()) != null) { s = s.append(sResponse); System.out.println("Response: " + res.getStatusLine().getStatusCode()); }`enter code here` System.out.println("Response: " + s.toString()); } catch `enter code here`(ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
- Tomas de cajones niños vistas superpuestas
- Evento del dispositivo Android onConfigurationChanged no controla la orientación