android利用 MultipartEntity同时上传图片,文件和内容小结

        最近在做一个需求的时候,需要要求同时在HTTP请求的时候,发送图片和文件,还有文本内容。上网搜索了一下,找到一个利用MultipartEntity实现的方式。

一.主要方法:

1. 利用MultipartEntity上传图片,文件和文本内容

 private String actionUrl = "http://test.uploadimgae.dest/test";
 
    public static int newPost(String actionUrl,  String imagepath,String content)
    {
        int statusCode = -1;
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 1000 * 10);
        HttpConnectionParams.setSoTimeout(httpParameters, 1000 * 10);
        HttpConnectionParams.setTcpNoDelay(httpParameters, true);

        HttpClient httpclient = new DefaultHttpClient(httpParameters);

        HttpPost httppost = new HttpPost(actionUrl);
        MultipartEntity mpEntity = new MultipartEntity();
        try
        {
             File imageFile = new File(imagepath);
           if (!imageFile.exists())
            {
               Log.e(TAG, "newPost" + "http=" + 999);
                statusCode = 999;
            }
            if (params != null)
             {
                 for (Map.Entry<String, String> entry : params.entrySet())
                 {
                     String key = entry.getKey().toString();
                     String value = entry.getValue().toString();
                     Log.e(TAG, "newPost" + "KEY:" + key + ",Value:" + value);
                     mpEntity.addPart(key, new StringBody(value));
                }
            }

             
            //图片域和文件域
             FileBody file = new FileBody(imageFile);
            mpEntity.addPart("picPath", file);
            mpEntity.addPart("picName", new StringBody(file.getFilename()));
            httppost.setEntity(mpEntity);
            HttpResponse httpResponse = httpclient.execute(httppost);
            statusCode = httpResponse.getStatusLine().getStatusCode();
            Log.e(TAG, "newPost" + "statusCode=" + statusCode);
            if (statusCode == 200)
            {
                StringBuilder builder = new StringBuilder();
                BufferedReader bufferedReader = null;
                try
                {
                    bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
                    for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine())
                    {
                        builder.append(s);
                    }
                    Log.e(TAG, "newPost"+"builder.toString()=" + builder.toString());
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(builder.toString());
                    String result = jsonObject.getString("result");
                    Log.e("newPost", "jsonObject=" + jsonObject);
                    Log.e("newPost", "jsonObject.result=" + result);
                }
                catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return statusCode;
    }
    

2.利用HTTP post方式发送内容

public void httpPostSendContent(String content) {
  String result = "";
  String url = http://test.uploadimgae.dest/test;
  HttpClient httpClient = new DefaultHttpClient();
  HttpPost httpRequest = new HttpPost(); // 创建HttpPost对象
  List<NameValuePair> params = new ArrayList<NameValuePair>();
  params.add(new BasicNameValuePair("params", "post"));
  params.add(new BasicNameValuePair("content", content));
  try {
   httpRequest.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
   HttpResponse httpResponse = httpClient.execute(httpRequest);
   if (httpResponse.getStatusLine().getStatusCode() == 200) {
    result += EntityUtils.toString(httpResponse.getEntity());
   } else {
    result = "请求失败";
   }
   Log.e(TAG, "result := " + result);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
  

 

二.网上找到一个demo是

1.MainActivity

package com.example.uploadimage;

import java.io.File;
import java.io.FileNotFoundException;

import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity
{
    private ImageView mImageView;
    private Button mButton;
    private String mImgPaths = "";
    public static final String[] addPhoto = new String[]
    { "现在拍摄", "从相册选择", "取消" };

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mImageView = (ImageView) findViewById(R.id.id_zhaopian_img);
        mButton = (Button) findViewById(R.id.id_commit_btn);

        mImageView.setOnClickListener(new OnClickListener()
        {
            @SuppressWarnings("deprecation")
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                showDialog(0);
            }
        });

        mButton.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                // TODO Auto-generated method stub
                UploadIMG uploadIMG = new UploadIMG();
                if(mImgPaths==null||mImgPaths.equals(""))
                {
                    Toast.makeText(MainActivity.this, "请添加图片", Toast.LENGTH_SHORT).show();
                    return;
                }

                //调用上传图片入口
                uploadIMG.upLoadImg(null, mImgPaths);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        // TODO Auto-generated method stub
        Bitmap bitmap = null;

        // if (resultCode == RESULT_OK)
        {
            if (requestCode == 0)
            {
                File imgFile = new File(Environment.getExternalStorageDirectory() + "/" + "carPhoto" + "/" + "Car.jpg");
                try
                {
                    Uri imgUri = Uri.parse(android.provider.MediaStore.Images.Media.insertImage(getContentResolver(),
                            imgFile.getAbsolutePath(), null, null));

                    String[] proj =
                    { MediaStore.Images.Media.DATA };
                    @SuppressWarnings("deprecation")
                    Cursor cursor = managedQuery(imgUri, proj, null, null, null);
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    cursor.moveToFirst();
                    String path = cursor.getString(column_index);
                    mImgPaths=path;
                   
                    ContentResolver cr = this.getContentResolver();
                    bitmap = BitmapFactory.decodeStream(cr.openInputStream(imgUri));

                    Log.d("onActivityResult", "u=" + imgUri + "/bitmap=" + bitmap);
                    bitmap = ThumbnailUtils.extractThumbnail(bitmap,260, 200);
                    mImageView.setImageBitmap(bitmap);
                }
                catch (FileNotFoundException e)
                {
                    e.printStackTrace();
                }
            }
            else if (requestCode == 1)
            {
                if (data == null)
                {
                    return;
                }
                Uri uri = data.getData();
                ContentResolver cr = this.getContentResolver();
                Log.d("onActivityResult", "uri=" + uri + "/uri.path=" + uri.getPath());

                String[] proj =
                { MediaStore.Images.Media.DATA };
                @SuppressWarnings("deprecation")
                Cursor cursor = managedQuery(uri, proj, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                String path = cursor.getString(column_index);
                mImgPaths=path;
                try
                {
                    bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri));
                    bitmap = ThumbnailUtils.extractThumbnail(bitmap, 70, 70);
                    /* 将Bitmap设定到ImageView */
                    mImageView.setImageBitmap(bitmap);
                }
                catch (FileNotFoundException e)
                {
                    Log.e("onActivityResult", e.getMessage(), e);
                }
            }
        }
    }

    @Override
    protected Dialog onCreateDialog(int id)
    {
        // TODO Auto-generated method stub
        AlertDialog dialog = null;
        AlertDialog.Builder builder = null;
        switch (id)
        {
        case 0:
            builder = new AlertDialog.Builder(this);
            builder.setTitle("添加爱车照片");
            builder.setItems(addPhoto, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    // TODO Auto-generated method stub
                    if (which == 0)
                    {
                        String haveSD = Environment.getExternalStorageState();
                        if (!haveSD.equals(Environment.MEDIA_MOUNTED))
                        {
                            Toast.makeText(MainActivity.this, "存储卡不可用", Toast.LENGTH_LONG).show();
                            return;
                        }
                        File dir = new File(Environment.getExternalStorageDirectory() + "/" + "carPhoto");
                        if (!dir.exists())
                        {
                            dir.mkdirs();
                        }
                        Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        File imgFile = new File(dir, "Car.jpg");
                        Uri u = Uri.fromFile(imgFile);
                        intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
                        startActivityForResult(intent, 0);
                    }
                    if (which == 1)
                    {
                        Intent intent = new Intent("android.intent.action.GET_CONTENT");
                        intent.addCategory("android.intent.category.OPENABLE");
                        intent.setType("image/*");
                        MainActivity.this.startActivityForResult(intent, 1);
                    }
                }
            });
            dialog = builder.create();
            break;

        default:
            break;
        }
        return dialog;
    }
}

2.上传图片

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;

public class UploadIMG
{
    public static final String TAG = "UploadIMG";
    private String actionUrl = "http://192.168.1.165:8080/AiKuPai4SService/server/accident";
  
    public static int newPost(String actionUrl, Map<String, String> params, String imagepath)
    {
        int statusCode = -1;
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 1000 * 10);
        HttpConnectionParams.setSoTimeout(httpParameters, 1000 * 10);
        HttpConnectionParams.setTcpNoDelay(httpParameters, true);

        HttpClient httpclient = new DefaultHttpClient(httpParameters);

        HttpPost httppost = new HttpPost(actionUrl);
        MultipartEntity mpEntity = new MultipartEntity();
        try
        {
            File imageFile = new File(imagepath);
            if (!imageFile.exists())
            {
                Log.e(TAG, "newPost" + "http=" + 999);
                statusCode = 999;
            }
            if (params != null)
            {
                for (Map.Entry<String, String> entry : params.entrySet())
                {
                    String key = entry.getKey().toString();
                    String value = entry.getValue().toString();
                    Log.e(TAG, "newPost" + "KEY:" + key + ",Value:" + value);
                    mpEntity.addPart(key, new StringBody(value));
                }
            }
           
            FileBody file = new FileBody(imageFile);
            mpEntity.addPart("picPath", file);
            mpEntity.addPart("picName", new StringBody(file.getFilename()));
            httppost.setEntity(mpEntity);
            HttpResponse httpResponse = httpclient.execute(httppost);
            statusCode = httpResponse.getStatusLine().getStatusCode();
            Log.e(TAG, "newPost" + "statusCode=" + statusCode);
            if (statusCode == 200)
            {
                StringBuilder builder = new StringBuilder();
                BufferedReader bufferedReader = null;
                try
                {
                    bufferedReader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));
                    for (String s = bufferedReader.readLine(); s != null; s = bufferedReader.readLine())
                    {
                        builder.append(s);
                    }
                    Log.e(TAG, "newPost"+"builder.toString()=" + builder.toString());
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(builder.toString());
                    String result = jsonObject.getString("result");
                    Log.e("newPost", "jsonObject=" + jsonObject);
                    Log.e("newPost", "jsonObject.result=" + result);
                }
                catch (IOException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return statusCode;
    }

    private class UploadImageTask extends AsyncTask<String, String, String>
    {
        String mServiceUrl;
        String mFilePaths;

        public UploadImageTask(String serviceUrl, String filePaths)
        {
            this.mServiceUrl = serviceUrl;
            Log.e(TAG, "serviceUrl := " + serviceUrl);
            this.mFilePaths = filePaths;
        }

        @Override
        protected String doInBackground(String... params)
        {
            // TODO Auto-generated method stub
            HashMap<String, String> userInfo = new HashMap<String, String>();
            userInfo.put("username", "张三");
            userInfo.put("pwd", "123456");
            userInfo.put("age", "23");

            //通过异步类函数上传图片路径

            newPost(mServiceUrl, userInfo, mFilePaths);
            return null;
        }
    }

    public void upLoadImg(String serviceUrl, String filePaths)
    {
        UploadImageTask task = new UploadImageTask(actionUrl, filePaths);
        task.execute("");
    }
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值