Android okHttp addFormDataPart dinámicamente para múltiples imágenes

Hola AndroidUploaders,

Había dado la respuesta Subiendo un archivo grande en multipart usando OkHttp pero estoy atrapado con la carga múltiple de la imagen.

Quiero cargar dinámicamente de 1 a 10 imágenes a la vez.

RequestBody requestBody = new MultipartBuilder() .type(MultipartBuilder.FORM) .addFormDataPart(KEY_PHOTO_CAPTION, photoCaption) .addFormDataPart(KEY_FILE, "profile.png", RequestBody.create(MEDIA_TYPE_PNG, sourceFile)) .build(); 

Tengo ArrayList de PhotoCaption clase que tiene captionPhoto y urlPhoto así que ¿cómo puedo addFormDataPart ()

Estoy pensando en hacer bucle y llamar a esta función que muchas veces de tamaño ArrayList .

¿Hay alguna solución para addFormDataPart () utilizar dinámicamente?

Esta respuesta es para OkHttp2

Para OkHttp3 Usted puede ver este post .

Para la imagen múltiple usted apenas necesita funcionar el lazo según su requisito, la parte restante relacionada con la petición será igual que usted.

  // final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png"); final MediaType MEDIA_TYPE=MediaType.parse(AppConstant.arrImages.get(i).getMediaType()); //If you can have multiple file types, set it in ArrayList MultipartBuilder buildernew = new MultipartBuilder().type(MultipartBuilder.FORM) .addFormDataPart("title", title) for (int i = 0; i < AppConstants.arrImages.size(); i++) { File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), TEMP_FILE_NAME + i + ".png"); if (f.exists()) { buildernew.addFormDataPart(TEMP_FILE_NAME + i, TEMP_FILE_NAME + i + FILE_EXTENSION, RequestBody.create(MEDIA_TYPE, f)); } } RequestBody requestBody = buildernew.build(); Request request = new Request.Builder() .url(Url.URL + Url.INSERT_NEWS) .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); return response.body().string(); 

No se olvide de borrar temp. Archivos que ha subido si no sirve de nada.

Aquí he creado la función para cargar múltiples imágenes.

 /** * Here I am uploading MultipleImages from List of photoCaption * Sending photoCaption with URL and Caption of Photo... * * @param albumId * @param photoCaptions * @return */ public static JSONObject uploadAlbumImage(String albumId, ArrayList<PhotoCaption> photoCaptions) { try { MultipartBuilder multipartBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); int length = photoCaptions.size(); int noOfImageToSend = 0; for(int i = 0; i < length; i++) { /** * Getting Photo Caption and URL */ PhotoCaption photoCaptionObj = photoCaptions.get(i); String photoUrl = photoCaptionObj.getPhotoUrl(); String photoCaption = photoCaptionObj.getPhotoCaption(); File sourceFile = new File(photoUrl); if(sourceFile.exists()) { /** Changing Media Type whether JPEG or PNG **/ final MediaType MEDIA_TYPE = MediaType.parse(FileUtils.getExtension(photoUrl).endsWith("png") ? "image/png" : "image/jpeg"); /** Adding in MultipartBuilder **/ multipartBuilder.addFormDataPart(KEY_IMAGE_CAPTION + i, photoCaption); multipartBuilder.addFormDataPart(KEY_IMAGE_NAME + i, sourceFile.getName(), RequestBody.create(MEDIA_TYPE, sourceFile)); /** Counting No Of Images **/ noOfImageToSend++; } } RequestBody requestBody = multipartBuilder .addFormDataPart(KEY_ALBUM_ID, albumId) .addFormDataPart(KEY_IMAGE_COUNT, String.valueOf(noOfImageToSend)) .build(); Request request = new Request.Builder() .url(URL_ALBUM_UPLOAD_IMAGE) .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); /** Your Response **/ String responseStr = response.body().string(); Log.i(TAG, "responseStr : "+ responseStr); return new JSONObject(responseStr); } catch (UnknownHostException | UnsupportedEncodingException e) { Log.e(TAG, "Error: " + e.getLocalizedMessage()); } catch (Exception e) { Log.e(TAG, "Other Error: " + e.getLocalizedMessage()); } return null; } 

Espero que te ayude.

  • Subida de archivos con okhttp
  • ¿Cómo puedo fijar un certificado con OKHTTP cuadrado?
  • ¿Qué está causando HTTP FALLA: java.net.SocketException: Socket cerrado?
  • OkHttp cuerpo del poste del gzip
  • NoSuchMethodError si estoy usando okhttp 2.0 y la última actualización?
  • ¿Hay un reemplazo para el RequestInterceptor en Retrofit 2?
  • Retrofit y OkHttpClient, catch timeout de conexión en el método de fallo
  • Consiguió este error con retrofit2 y OkHttp3. No se puede resolver el host "<host-name>": ninguna dirección asociada con el nombre de host
  • Cómo agregar varios encabezados con ok Http
  • Retrofit detectó un OkHttp no admitido en el error classpath en OKHttp 2.0
  • Android OkHttp cómo manejar ETag
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.