¿Cómo subir datos e imágenes de formularios de varias partes al servidor en Android?

Código de estado 500 durante la carga de imagen de entidad de múltiples partes al servidor en código de Android

Forma Html: (puede agregar imagen exitosamente al servidor)

Sample Picture Upload Form Submit

API key:

Login:
Password:

Property ID:
Picture File:




Código de Android: (proporciona el código de estado 500)

  HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( "http://sofes.miximages.com/android/Test.jpg"); entity.addPart("picture", new FileBody(file)); httppost.setEntity(entity); HttpResponse response = httpclient.execute(httppost); Log.e("test", "SC:" + response.getStatusLine().getStatusCode()); HttpEntity resEntity = response.getEntity(); BufferedReader reader = new BufferedReader(new InputStreamReader( response.getEntity().getContent(), "UTF-8")); String sResponse; StringBuilder s = new StringBuilder(); while ((sResponse = reader.readLine()) != null) { s = s.append(sResponse); } Log.e("test", "Response: " + s); } catch (ClientProtocolException e) { } catch (IOException e) { } 

Si como yo estuvieras luchando con la carga de varias partes. Aquí hay una solución que usa el 95% del código de este fragmento de Android.

 public String multipartRequest(String urlTo, Map parmas, String filepath, String filefield, String fileMimeType) throws CustomException { HttpURLConnection connection = null; DataOutputStream outputStream = null; InputStream inputStream = null; String twoHyphens = "--"; String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; String lineEnd = "\r\n"; String result = ""; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String[] q = filepath.split("/"); int idx = q.length - 1; try { File file = new File(filepath); FileInputStream fileInputStream = new FileInputStream(file); URL url = new URL(urlTo); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("User-Agent", "Android Multipart HTTP Client 1.0"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + q[idx] + "\"" + lineEnd); outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); // Upload POST Data Iterator keys = parmas.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); String value = parmas.get(key); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd); outputStream.writeBytes("Content-Type: text/plain" + lineEnd); outputStream.writeBytes(lineEnd); outputStream.writeBytes(value); outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); if (200 != connection.getResponseCode()) { throw new CustomException("Failed to upload code:" + connection.getResponseCode() + " " + connection.getResponseMessage()); } inputStream = connection.getInputStream(); result = this.convertStreamToString(inputStream); fileInputStream.close(); inputStream.close(); outputStream.flush(); outputStream.close(); return result; } catch (Exception e) { logger.error(e); throw new CustomException(e); } } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } 

Código de llamada:

 //setup params Map params = new HashMap(2); params.put("foo", hash); params.put("bar", caption); String result = multipartRequest(URL_UPLOAD_VIDEO, params, pathToVideoFile, "video", "video/mp4"); //next parse result string 

Aquí está la solución que funcionó para mí sin HTTPCore externo y tales libs. Me enfrentaba al problema de los métodos de 64 K, por lo que no me queda otra opción para evitar las bibliotecas HTTPCore

 import java.util.List; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; /** * This utility class provides an abstraction layer for sending multipart HTTP * POST requests to a web server. * * @author www.codejava.net */ public class MultipartUtility { private final String boundary; private static final String LINE_FEED = "\r\n"; private HttpURLConnection httpConn; private String charset; private OutputStream outputStream; private PrintWriter writer; /** * This constructor initializes a new HTTP POST request with content type * is set to multipart/form-data * * @param requestURL * @param charset * @throws IOException */ public MultipartUtility(String requestURL, String charset) throws IOException { this.charset = charset; // creates a unique boundary based on time stamp boundary = "===" + System.currentTimeMillis() + "==="; URL url = new URL(requestURL); httpConn = (HttpURLConnection) url.openConnection(); httpConn.setUseCaches(false); httpConn.setDoOutput(true); // indicates POST method httpConn.setDoInput(true); httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); httpConn.setRequestProperty("User-Agent", "CodeJava Agent"); httpConn.setRequestProperty("Test", "Bonjour"); outputStream = httpConn.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true); } /** * Adds a form field to the request * * @param name field name * @param value field value */ public void addFormField(String name, String value) { writer.append("--" + boundary).append(LINE_FEED); writer.append("Content-Disposition: form-data; name=\"" + name + "\"") .append(LINE_FEED); writer.append("Content-Type: text/plain; charset=" + charset).append( LINE_FEED); writer.append(LINE_FEED); writer.append(value).append(LINE_FEED); writer.flush(); } /** * Adds a upload file section to the request * * @param fieldName name attribute in  * @param uploadFile a File to be uploaded * @throws IOException */ public void addFilePart(String fieldName, File uploadFile) throws IOException { String fileName = uploadFile.getName(); writer.append("--" + boundary).append(LINE_FEED); writer.append( "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"") .append(LINE_FEED); writer.append( "Content-Type: " + URLConnection.guessContentTypeFromName(fileName)) .append(LINE_FEED); writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED); writer.append(LINE_FEED); writer.flush(); FileInputStream inputStream = new FileInputStream(uploadFile); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append(LINE_FEED); writer.flush(); } /** * Adds a header field to the request. * * @param name - name of the header field * @param value - value of the header field */ public void addHeaderField(String name, String value) { writer.append(name + ": " + value).append(LINE_FEED); writer.flush(); } /** * Completes the request and receives response from the server. * * @return a list of Strings as response in case the server returned * status OK, otherwise an exception is thrown. * @throws IOException */ public List finish() throws IOException { List response = new ArrayList(); writer.append(LINE_FEED).flush(); writer.append("--" + boundary + "--").append(LINE_FEED); writer.close(); // checks server's status code first int status = httpConn.getResponseCode(); if (status == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader( httpConn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { response.add(line); } reader.close(); httpConn.disconnect(); } else { throw new IOException("Server returned non-OK status: " + status); } return response; } } 

USO

 private void uploadMedia() { try { String charset = "UTF-8"; File uploadFile1 = new File("/sdcard/myvideo.mp4"); String requestURL = Data.BASE_URL+Data.URL_UPLOAD_REACTION_TEST; MultipartUtility multipart = new MultipartUtility(requestURL, charset); // multipart.addHeaderField("User-Agent", "CodeJava"); // multipart.addHeaderField("Test-Header", "Header-Value"); multipart.addFormField("friend_id", "Cool Pictures"); multipart.addFormField("userid", "Java,upload,Spring"); multipart.addFilePart("uploadedfile", uploadFile1); List response = multipart.finish(); Log.v("rht", "SERVER REPLIED:"); for (String line : response) { Log.v("rht", "Line : "+line); } } catch (Exception e) { e.printStackTrace(); } } 

Código PHP para aceptar la carga

  

El código de estado 500 significa que hay algo mal con la configuración del servidor. No está relacionado con tu código. Ver http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html .

Intenta esto puede ayudarte

 File file = new File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM).toString() + "/Camera/Test.jpg"); entity.addPart("picture", new FileBody(file,"image/jpg")); //Update here 

hola después de tener un montón de prueba de prueba y error finalmente consiguió este amigos

// sobre cómo subir imágenes a Facebook usando gráficos apis

  Bundle params = new Bundle(); params.putByteArray("multipart/form-data",byteArray); params.putString("caption",txtcaption.getText().toString()); /* make the API call */ new GraphRequest( AccessToken.getCurrentAccessToken(), "/me/photos", params, HttpMethod.POST, new GraphRequest.Callback() { public void onCompleted(GraphResponse response) { /* handle the result */ Log.e("responseImagedata---", response.toString()); } } ).executeAsync();