How to Send Multiple Images to Server Using Multipartentity from Android

Sending multiple images to the server from android

Yes, there is a better way to upload or download multiple files.
first of all you must define an AsyncTask, and in his doInBackground function you must write your code to upload/download the file.

And by that, first of all your view will not freeze while downloading/uploading. The multiple files will be lunched asynchronously. and you can call it as easy as the following:

new MyAsyncTask(fileUrl1).execute();
new MyAsyncTask(fileUrl2).execute();

This is a better and more manageable method in order to use HTTP requests.

Hope that I've helped you.
Good Luck

Retrofit Uploading multiple images to a single key

We can use MultipartBody.Part array to upload an array of images to a single key.
Here is the solution

WebServicesAPI

@Multipart
@POST(WebServices.UPLOAD_SURVEY)
Call<UploadSurveyResponseModel> uploadSurvey(@Part MultipartBody.Part[] surveyImage,
@Part MultipartBody.Part propertyImage,
@Part("DRA") RequestBody dra);

Here is the method for uploading the files.

private void requestUploadSurvey () {
File propertyImageFile = new File(surveyModel.getPropertyImagePath());
RequestBody propertyImage = RequestBody.create(MediaType.parse("image/*"),
propertyImageFile);
MultipartBody.Part propertyImagePart = MultipartBody.Part.createFormData("PropertyImage",
propertyImageFile.getName(),
propertyImage);

MultipartBody.Part[] surveyImagesParts = new MultipartBody.Part[surveyModel.getPicturesList()
.size()];

for (int index = 0; index <
surveyModel.getPicturesList()
.size(); index++) {
Log.d(TAG,
"requestUploadSurvey: survey image " +
index +
" " +
surveyModel.getPicturesList()
.get(index)
.getImagePath());
File file = new File(surveyModel.getPicturesList()
.get(index)
.getImagePath());
RequestBody surveyBody = RequestBody.create(MediaType.parse("image/*"),
file);
surveyImagesParts[index] = MultipartBody.Part.createFormData("SurveyImage",
file.getName(),
surveyBody);
}

final WebServicesAPI webServicesAPI = RetrofitManager.getInstance()
.getRetrofit()
.create(WebServicesAPI.class);
Call<UploadSurveyResponseModel> surveyResponse = null;
if (surveyImagesParts != null) {
surveyResponse = webServicesAPI.uploadSurvey(surveyImagesParts,
propertyImagePart,
draBody);
}
surveyResponse.enqueue(this);
}

Upload multiple images to server from Android app

You can simply put it in a loop. Assuming you have an array of files (in this example called myFiles), you would just do something like this. Bear in mind that it's important of each iteration to create a new object of everything, so this way you're making sure you're sending always a different and independent object.

int i = 0;

String[] myFiles = { "C:\path1.jpg", "C:\path2.jpg" };

for (String selectedPath : myFiles) {
File file = new File(selectedPath);
Bitmap bitmap = decodeFile(file);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();

try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);

ByteArrayBody bab = new ByteArrayBody(data, "test.jpg");

MultipartEntity reqEntity = new MultipartEntity();

reqEntity.addPart("path[" + String.valueOf(i++) + "]", bab);

post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
response_str = EntityUtils.toString(resEntity);
}
catch (...) { ... }
}

how do i upload multiple images using Multiparty Entity in Android

I use the following code in android to upload the multiples images from android

            private void doFileUpload(List<Uri> mDetials){
List<File> mFiles=new ArrayList<>();
for(int i=0;i<mDetials.size();i++){
String mFileLocation=getPath(getApplicationContext(),mDetials.get(i));
File file = new File(mFileLocation);
mFiles.add(file);
}
String urlString = "php_file_link.php";
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
List<FileBody> mFileBody=new ArrayList<>();
for(int i=0;i<mFiles.size();i++){
FileBody bin1 = new FileBody(mFiles.get(i));
mFileBody.add(bin1);
}
MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
for(int i=0;i< mFileBody.size();i++){
reqEntity.addPart("uploadedfile"+i,mFileBody.get(i));
}
reqEntity.addTextBody("size",""+mDetials.size(), ContentType.TEXT_PLAIN);
post.setEntity(reqEntity.build());
HttpResponse response = client.execute(post);
HttpEntity resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);

if (resEntity != null) {
Log.i("RESPONSE", response_str);
dialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
try {
Toast.makeText(getApplicationContext(), response_str, Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}});
}
} catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
dialog.dismiss();
}
}

I use the following php code to upload on server

$size = $_REQUEST['size'];
for ($x = 0; $x < $size; $x++) {
$target_path="../GizboImages/customer_care/";
$target_path=$target_path.basename( $_FILES["uploadedfile".$x]['name']);
if(move_uploaded_file($_FILES["uploadedfile".$x]['tmp_name'], $target_path)) ;
}

send multiple image to server : One image sending thrice to server issue

entity.addPart("filename[0]", new ByteArrayBody(data,"image/jpeg", params[1]));
entity.addPart("filename[1]", new ByteArrayBody(data,"image/jpeg", params[1]));
entity.addPart("filename[2]", new ByteArrayBody(data,"image/jpeg", params[1]));

You are sending same file three times that's the problem.


Better to put images path in SharedPrefrence.

    byte[] data1 = null,data2= null,data3= null;

if(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).contains("endum_image_0"))
{ up_image1 = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("endum_image_0", "");
bitmap = BitmapFactory.decodeFile(up_image1, options1);
bitmap.compress(CompressFormat.JPEG, 100, bos1);
data1 = bos1.toByteArray();
}
if(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).contains("endum_image_1"))
{ up_image2 = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("endum_image_1", "");
bitmap = BitmapFactory.decodeFile(up_image2, options1);
bitmap.compress(CompressFormat.JPEG, 100, bos2);
data2 = bos2.toByteArray();
}

if(PreferenceManager.getDefaultSharedPreferences(getBaseContext()).contains("endum_image_2"))
{ up_image3 = PreferenceManager.getDefaultSharedPreferences(getBaseContext()).getString("endum_image_2", "");
bitmap = BitmapFactory.decodeFile(up_image3, options1);
bitmap.compress(CompressFormat.JPEG, 100, bos3);
data3 = bos3.toByteArray();
}

if byte array have data then only send it to server

    if(data1!=null){
entity.addPart("files[]", new ByteArrayBody(data1,"image/jpeg", "u1.jpg"));
}
if(data2!=null){
entity.addPart("files[]", new ByteArrayBody(data2,"image/jpeg", "u2.jpg"));
}

if(data3!=null){
entity.addPart("files[]", new ByteArrayBody(data3,"image/jpeg", "u3.jpg"));
}

Sending Data on server:

    HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
MultipartEntity entity = new MultipartEntity();
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);

BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));

StringBuilder s = new StringBuilder();

while ((sResponse = reader.readLine()) != null)
{
s = s.append(sResponse);
}

if(response.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
return s.toString();
}else
{
return "{\"status\":\"false\",\"message\":\"Some error occurred\"}";
}

Fastest Way to Upload Multiple Image to Server in android

There are many methods to upload more images to the server.. one could be including two libraries: apache-mime4j-0.6.jar and httpmime-4.0.1.jar.. After that create your java main code:

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class FileUploadTest extends Activity {

private static final int SELECT_FILE1 = 1;
private static final int SELECT_FILE2 = 2;
String selectedPath1 = "NONE";
String selectedPath2 = "NONE";
TextView tv, res;
ProgressDialog progressDialog;
Button b1,b2,b3;
HttpEntity resEntity;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

tv = (TextView)findViewById(R.id.tv);
res = (TextView)findViewById(R.id.res);
tv.setText(tv.getText() + selectedPath1 + "," + selectedPath2);
b1 = (Button)findViewById(R.id.Button01);
b2 = (Button)findViewById(R.id.Button02);
b3 = (Button)findViewById(R.id.upload);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
openGallery(SELECT_FILE1);
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
openGallery(SELECT_FILE2);
}
});
b3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(!(selectedPath1.trim().equalsIgnoreCase("NONE")) && !(selectedPath2.trim().equalsIgnoreCase("NONE"))){
progressDialog = ProgressDialog.show(FileUploadTest.this, "", "Uploading files to server.....", false);
Thread thread=new Thread(new Runnable(){
public void run(){
doFileUpload();
runOnUiThread(new Runnable(){
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});

}

public void openGallery(int req_code){

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select file to upload "), req_code);
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {

if (resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
if (requestCode == SELECT_FILE1)
{
selectedPath1 = getPath(selectedImageUri);
System.out.println("selectedPath1 : " + selectedPath1);
}
if (requestCode == SELECT_FILE2)
{
selectedPath2 = getPath(selectedImageUri);
System.out.println("selectedPath2 : " + selectedPath2);
}
tv.setText("Selected File paths : " + selectedPath1 + "," + selectedPath2);
}
}

public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

private void doFileUpload(){

File file1 = new File(selectedPath1);
File file2 = new File(selectedPath2);
String urlString = "http://10.0.2.2/upload_test/upload_media_test.php";
try
{
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
FileBody bin1 = new FileBody(file1);
FileBody bin2 = new FileBody(file2);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("uploadedfile1", bin1);
reqEntity.addPart("uploadedfile2", bin2);
reqEntity.addPart("user", new StringBody("User"));
post.setEntity(reqEntity);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
if (resEntity != null) {
Log.i("RESPONSE",response_str);
runOnUiThread(new Runnable(){
public void run() {
try {
res.setTextColor(Color.GREEN);
res.setText("n Response from server : n " + response_str);
Toast.makeText(getApplicationContext(),"Upload Complete. Check the server uploads directory.", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
catch (Exception ex){
Log.e("Debug", "error: " + ex.getMessage(), ex);
}
}
}

Now your layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Multiple File Upload from CoderzHeaven"
/>
<Button
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get First File">
</Button>
<Button
android:id="@+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Second File">
</Button>
<Button
android:id="@+id/upload"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Upload">
</Button>
<TextView
android:id="@+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Selected File path : "
/>

<TextView
android:id="@+id/res"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>

of course, include the internet permission in your manifest:

<uses-permission android:name="android.permission.INTERNET" />

And voilà. Anyway i followed this example in my case: http://www.coderzheaven.com/2011/08/16/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/ try to see there.. There are 4 methods to upload multiple files. See which you like



Related Topics



Leave a reply



Submit