在Android中将多个图像上传到服务器的最快方法 [英] Fastest Way to Upload Multiple Image to Server in android

查看:42
本文介绍了在Android中将多个图像上传到服务器的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've multiple images to upload in server and i've a method for upload single image to server. now I'm using this method to send multiple images by creating loop for each images.

是否有最快的方法将多个图像发送到服务器?预先感谢...

Is there any fastest way to send multiple images to server?. Thanks in advance...

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

推荐答案

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

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

现在您的布局:

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

当然,请在清单中包括Internet权限:

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

这篇关于在Android中将多个图像上传到服务器的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆