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:

 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.

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(); } 
  • declarando el tipo de mime para un "archivo personalizado" que se va a enviar a través de bluetooth
  • Abrir mi aplicación para un determinado archivo y extensión de URL - intento-filtro no funciona como se pretende
  • Tipo de MIME para directorios en Android
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.