【问题标题】:Fastest Way to Upload Multiple Image to Server in android在android中将多个图像上传到服务器的最快方法
【发布时间】:2015-11-25 12:02:56
【问题描述】:

我有多个图像要上传到服务器,我有一种方法可以将单个图像上传到服务器。现在我正在使用这种方法通过为每个图像创建循环来发送多个图像。

有没有最快的方法将多张图片发送到服务器?提前谢谢...

public int imageUpload(GroupInfoDO infoDO) {
        ObjectMapper mapper = new ObjectMapper();
        int groupId = 0;
        try {
            Bitmap bm = BitmapFactory.decodeFile(infoDO.getDpUrl());
            String fileName = infoDO.getDpUrl().substring(
                    infoDO.getDpUrl().lastIndexOf('/') + 1,
                    infoDO.getDpUrl().length());
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.JPEG, 75, bos);
            byte[] data = bos.toByteArray();
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(
                    "http://192.168.1.24:8081/REST/groupreg/upload");
            ByteArrayBody bab = new ByteArrayBody(data,
                    "application/octet-stream");
            MultipartEntity reqEntity = new MultipartEntity(
                    HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("uploadFile", bab);
            reqEntity.addPart("name", new StringBody(fileName));
            reqEntity.addPart("grpId", new StringBody(infoDO.getGlobalAppId()
                    + ""));
            postRequest.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(postRequest);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity httpEntity = response.getEntity();
                String json = EntityUtils.toString(httpEntity);
                Map<String, Object> mapObject = mapper.readValue(json,
                        new TypeReference<Map<String, Object>>() {
                        });
                if ((mapObject != null)
                        && (mapObject.get("status").toString()
                                .equalsIgnoreCase("SUCCESS"))) {
                    groupId = (Integer.valueOf(mapObject.get("groupId")
                            .toString()));
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
            Log.e("log_tag", "Error in http connection " + e1.toString());
        }
        return groupId;
    } 

【问题讨论】:

  • 顺便说一句,这也取决于您的服务器。这样上传需要花费多少时间?现在可以用了吗?
  • 感谢您的回复。单个图像从服务器获得响应需要至少 10 秒。

标签: android server


【解决方案1】:

使用排球

private void uploadMultipleImage(){

    dialog = ogressDialog.show(WhatsappUpload.this,"","Loading...",false);
    String str[] = new String[MainActivity.bitmaps.size()];
    for(int i=0;i<MainActivity.bitmaps.size();i++){
        str[i] =  getStringImage(MainActivity.bitmaps.get(i));
    }
    imgs = TextUtils.join(",",str);
  //  Log.d("Sid","Join : " + TextUtils.join(",",str));

    String urlImages = "http://192.168.100.13/iupload/test_image.php";
    StringRequest stringRequest = new StringRequest(Request.Method.POST, urlImages,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    dialog.hide();
                    Log.d("Sid","Response : " + response.toString());
                    try {
                        JSONObject object = new JSONObject(response.toString());
                        Toast.makeText(getApplicationContext(),object.getString("msg"),Toast.LENGTH_SHORT).show();
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.d("Sid","JSON Exception : " + e);
                    }
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            dialog.hide();
            Log.d("Sid","Volly Error : " + error);
        }
    }){
        @Override
        protected Map<String, String> getParams() throws AuthFailureError {
            String cap  = !TextUtils.isEmpty(edtCaption.getText().toString()) ? edtCaption.getText().toString() : "Default Captions!";
            Map<String,String> params = new Hashtable<String, String>();
            params.put("captions",cap);
            params.put("images", imgs);
            return params;
        }
    };
    RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());
    requestQueue.add(stringRequest);
}


public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

【讨论】:

    【解决方案2】:

    试试这个代码。这对于上传一张或两张或三张图片很有用,并使用httpmime-4.2.1.jar

    活动

    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    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.HttpMultipartMode;
    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 org.json.JSONException;
    import org.json.JSONObject;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.database.Cursor;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Color;
    import android.graphics.drawable.ColorDrawable;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.Environment;
    import android.provider.MediaStore;
    import android.provider.MediaStore.MediaColumns;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.LinearLayout;
    import android.widget.ProgressBar;
    
    
    public class MultiImageActivity extends Activity {
    
        private static final int CAMERA_PICTURE = 1;
        private static final int GALLERY_PICTURE = 2;
        String filePath1 = null;
        String filePath2 = null;
        String filePath3 = null;
        Bitmap chosenImage;
        File destination = null;
        ImageView ivImg1, ivImg2, ivImg3;
    
        String img1Selected1 = null, img2Selected1 = null, img3Selected1 = null;
        String img1Selected2 = null, img2Selected2 = null, img3Selected2 = null;
    
        LinearLayout llImgHolder;
    
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_multi_image);
    
            Button btnImg1 = (Button) findViewById(R.id.btn_multi_img_1);
            Button btnImg2 = (Button) findViewById(R.id.btn_multi_img_2);
            Button btnImg3 = (Button) findViewById(R.id.btn_multi_img_3);
            Button btnUpload = (Button) findViewById(R.id.btn_multi_upload);
    
            llImgHolder = (LinearLayout) findViewById(R.id.ll_multi_img_holder);
    
            ivImg1 = (ImageView) findViewById(R.id.iv_multi_img1);
            ivImg2 = (ImageView) findViewById(R.id.iv_multi_img2);
            ivImg3 = (ImageView) findViewById(R.id.iv_multi_img3);
    
            btnImg1.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
                    img1Selected1 = "fulfilled";
                    choosePictureAction();
                }
            });
    
            btnImg2.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
                    if (img1Selected2 != null) {
                        img2Selected1 = "fulfilled";
                        choosePictureAction();
                    }else {
                        Log.e("Please select first image", "Please select first image");
                    }
                }
            });
    
            btnImg3.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
    
    
                    if (img2Selected2 != null) {
                        img3Selected1 = "fulfilled";
                        choosePictureAction();
                    }else {
                        Log.e("Please select second image", "Please select second image");
                    }
                }
            });
    
            btnUpload.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View v) {
    
                    String url="______________your_api________";
    
                    new uploadAsynTask().execute(url);
    
                }
            });
    
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == CAMERA_PICTURE && resultCode == RESULT_OK) {
                chosenImage = (Bitmap) data.getExtras().get("data");
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                chosenImage.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
                destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
                FileOutputStream fo;
                //filePath1 = destination.toString();
    
                if(img1Selected1 != null){
    
                    filePath1 = destination.toString();
                }else if(img2Selected1 != null){
    
                    filePath2 = destination.toString();
                }else if(img3Selected1 != null){
    
                    filePath3 = destination.toString();
                }
    
                try {
                    destination.createNewFile();
                    fo = new FileOutputStream(destination);
                    fo.write(bytes.toByteArray());
                    fo.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if(chosenImage != null){
                    if(img1Selected1 != null){
                        llImgHolder.setVisibility(View.VISIBLE);
                        ivImg1.setVisibility(View.VISIBLE);
    
                        img1Selected1 = null;
                        img1Selected2 = "fulfilled";
                        ivImg1.setImageBitmap(chosenImage);
                    }else if(img2Selected1 != null){
                        ivImg2.setVisibility(View.VISIBLE);
    
                        img2Selected1 = null;
                        img2Selected2 = "fulfilled";
                        ivImg2.setImageBitmap(chosenImage);
                    }else if(img3Selected1 != null){
                        ivImg3.setVisibility(View.VISIBLE);
    
                        img3Selected1 = null;
                        img3Selected2 = "fulfilled";
                        ivImg3.setImageBitmap(chosenImage);
                    }
    
                }
    
    
            } else if (requestCode == CAMERA_PICTURE
                    && resultCode == RESULT_CANCELED) {
    
            } else if (requestCode == GALLERY_PICTURE
                    && resultCode == RESULT_OK) {
                Uri selectedImageUri = data.getData();
                String[] projection = { MediaColumns.DATA };
                Cursor cursor = getContentResolver().query(selectedImageUri, projection, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaColumns.DATA);
                cursor.moveToFirst();
                String selectedImagePath = cursor.getString(column_index);
                destination = new File(selectedImagePath);
    
                if(img1Selected1 != null){
                    filePath1 = selectedImagePath;
                }else if(img2Selected1 != null){
                    filePath2 = selectedImagePath;
                }else if(img3Selected1 != null){
                    filePath3 = selectedImagePath;
                }
    
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(selectedImagePath, options);
                final int REQUIRED_SIZE = 200;
                int scale = 1;
                while (options.outWidth / scale / 2 >= REQUIRED_SIZE
                        && options.outHeight / scale / 2 >= REQUIRED_SIZE)
                    scale *= 2;
                options.inSampleSize = scale;
                options.inJustDecodeBounds = false;
                chosenImage = BitmapFactory.decodeFile(selectedImagePath, options);
    
                if(chosenImage!=null){
    
                    if(img1Selected1 != null){
                        llImgHolder.setVisibility(View.VISIBLE);
                        ivImg1.setVisibility(View.VISIBLE);
    
                        img1Selected1 = null;
                        img1Selected2 = "fulfilled";
                        ivImg1.setImageBitmap(chosenImage);
                    }else if(img2Selected1 != null){
                        ivImg2.setVisibility(View.VISIBLE);
    
                        img2Selected1 = null;
                        img2Selected2 = "fulfilled";
                        ivImg2.setImageBitmap(chosenImage);
                    }else if(img3Selected1 != null){
                        ivImg3.setVisibility(View.VISIBLE);
    
                        img3Selected1 = null;
                        img3Selected2 = "fulfilled";
                        ivImg3.setImageBitmap(chosenImage);
                    }
    
                }
    
            } else if (requestCode == GALLERY_PICTURE
                    && resultCode == RESULT_CANCELED) {
    
            }
        }
    
        private void choosePictureAction(){
    
            final CharSequence[] items = {"Camera", "Gallery", "Cancel"};
            AlertDialog.Builder builder = new AlertDialog.Builder(MultiImageActivity.this);
            builder.setTitle("Add Photo!");
            builder.setItems(items, new DialogInterface.OnClickListener() {
    
                @Override
                public void onClick(DialogInterface dialog, int which) {
    
                    if(items[which].equals("Camera")){
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent, CAMERA_PICTURE);
                    }else if(items[which].equals("Gallery")){
                        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, GALLERY_PICTURE);
                    }else if(items[which].equals("Cancel")){
                        dialog.dismiss();
                    }
    
                }
            });
    
            builder.show();
    
        }
    
    
        private class uploadAsynTask extends AsyncTask<String, Void, String>{
            ProgressDialog dialog;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(MultiImageActivity.this, null, null);
                ProgressBar spinner = new android.widget.ProgressBar(MultiImageActivity.this, null,android.R.attr.progressBarStyle);
                spinner.getIndeterminateDrawable().setColorFilter(Color.parseColor("#009689"), android.graphics.PorterDuff.Mode.SRC_IN);
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
                dialog.setContentView(spinner);
                dialog.setCancelable(false);
                dialog.show();
            }
            @Override
            protected String doInBackground(String... params) {
    
                Log.e("FilePathBin1", filePath1);
    
                File file1 = new File(filePath1);
                File file2 = null;
                File file3 = null;
    
                if(img2Selected2 != null){
                    Log.e("FilePathBin2", filePath2);
                    file2 = new File(filePath2);
                }
                if(img3Selected2 != null){
                    Log.e("FilePathBin3", filePath3);
                    file3 = new File(filePath3);
                }
    
                MultipartEntity reqEntity;
                HttpEntity resEntity;
                try {
                    HttpClient client = new DefaultHttpClient();
                    String postURL = params[0];
                    HttpPost post = new HttpPost(postURL);
    
                    FileBody bin1 = new FileBody(file1);
                    FileBody bin2 = null;
                    FileBody bin3 = null;
    
                    if(img2Selected2 != null){
    
                        bin2 = new FileBody(file2);
                    }
                    if(img3Selected2 != null){
    
                        bin3 = new FileBody(file3);
                    }
    
                    reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    
    
    
                    reqEntity.addPart("parking_title", new StringBody("Test13:26"));
                    reqEntity.addPart("latitude", new StringBody("10.12313213"));
                    reqEntity.addPart("longtitude", new StringBody("12.123213213"));
                    reqEntity.addPart("note", new StringBody("12"));
    
                    reqEntity.addPart("filename[0]", bin1);
    
                    if(img2Selected2 != null){
                        img2Selected2 = null;
                        reqEntity.addPart("filename[1]", bin2);
                    }
                    if(img3Selected2 != null){
                        img3Selected2 = null;
                        reqEntity.addPart("filename[2]", bin3);
                    }
                    reqEntity.addPart("spot_types[0]", new StringBody("1"));
                    reqEntity.addPart("spot_types[1]", new StringBody("2"));
                    reqEntity.addPart("spot_types[2]", new StringBody("3"));
                    reqEntity.addPart("spot_properties[0]", new StringBody("1"));
                    reqEntity.addPart("spot_properties[1]", new StringBody("2"));
                    reqEntity.addPart("spot_properties[2]", new StringBody("3"));
    
                    post.setEntity(reqEntity);
                    HttpResponse response = client.execute(post);
                    resEntity = response.getEntity();
                    String entityContentAsString = EntityUtils.toString(resEntity);
                    Log.d("stream:", entityContentAsString);
    
    
    
                    return entityContentAsString;
    
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
    
            }
    
    
    
            @Override
            protected void onPostExecute(String result) {
                super.onPostExecute(result);
    
    
                if(result != null){
                    dialog.dismiss();
                    Log.e("addPhotoResult", result);
    
                    filePath1 = null;
                    filePath2 = null;
                    filePath3 = null;
    
                    try {
                        JSONObject jsonObject = new JSONObject(result);
    
                        String error = jsonObject.getString("Error");
                        String message = jsonObject.getString("message");
    
                        Log.e("error", error);
                        Log.e("message", message);
    
    
    
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
    
    
    
            }
    
        }
    
    }
    

    Xml 布局

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dp"
        tools:context="com.app.multiimage.MultiImageActivity" >
    
        <Button
            android:id="@+id/btn_multi_img_1"
            android:layout_width="match_parent"
            android:layout_height="35dp"
            android:background="#000000"
            android:text="@string/multi_img1"
            android:textColor="#FFFFFF"
            android:textSize="12sp" />
    
        <Button
            android:id="@+id/btn_multi_img_2"
            android:layout_width="match_parent"
            android:layout_height="35dp"
            android:layout_below="@+id/btn_multi_img_1"
            android:layout_marginTop="10dp"
            android:background="#000000"
            android:text="@string/multi_img2"
            android:textColor="#FFFFFF"
            android:textSize="12sp" />
    
        <Button
            android:id="@+id/btn_multi_img_3"
            android:layout_width="match_parent"
            android:layout_height="35dp"
            android:layout_below="@+id/btn_multi_img_2"
            android:layout_marginTop="10dp"
            android:background="#000000"
            android:text="@string/multi_img3"
            android:textColor="#FFFFFF"
            android:textSize="12sp" />
    
        <LinearLayout
            android:id="@+id/ll_multi_img_holder"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/btn_multi_img_3"
            android:layout_marginTop="10dp"
            android:visibility="gone"
            android:orientation="horizontal" >
    
            <ImageView
                android:id="@+id/iv_multi_img1"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_weight="1"
                android:visibility="gone"
                android:contentDescription="@string/empty" />
    
            <ImageView
                android:id="@+id/iv_multi_img2"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_toRightOf="@+id/iv_multi_img1"
                android:layout_weight="1"
                android:visibility="gone"
                android:contentDescription="@string/empty" />
    
            <ImageView
                android:id="@+id/iv_multi_img3"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:visibility="gone"
                android:layout_toRightOf="@+id/iv_multi_img2"
                android:layout_weight="1"
                android:contentDescription="@string/empty" />
        </LinearLayout>
    
        <Button
            android:id="@+id/btn_multi_upload"
            android:layout_width="match_parent"
            android:layout_height="35dp"
            android:layout_below="@+id/ll_multi_img_holder"
            android:layout_marginTop="10dp"
            android:background="#000000"
            android:text="@string/multi_upload"
            android:textColor="#FFFFFF"
            android:textSize="12sp" />
    
    </RelativeLayout>
    

    清单

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

    【讨论】:

      【解决方案3】:

      有很多方法可以将更多图像上传到服务器。一种可能包括两个库:apache-mime4j-0.6.jar 和 httpmime-4.0.1.jar。然后创建您的 java 主代码:

      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);
              }
            }
      }
      

      现在你的布局:

      <?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>
      

      当然,在清单中包含互联网权限:

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

      然后瞧。无论如何,我在我的情况下遵循了这个示例:http://www.coderzheaven.com/2011/08/16/how-to-upload-multiple-files-in-one-request-along-with-other-string-parameters-in-android/ 尝试在那里查看.. 有 4 种方法可以上传多个文件。看看你喜欢哪个

      【讨论】:

      • 我也喜欢 HttpEntity,不过现在已经弃用了。
      • 如何添加这些库??请帮忙
      • @Md.AshikurRahman 来自build.gradle
      猜你喜欢
      • 1970-01-01
      • 2016-07-20
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-19
      • 1970-01-01
      相关资源
      最近更新 更多