android 批量上传图片

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了android 批量上传图片相关的知识,希望对你有一定的参考价值。

额外还需要NetUtil和服务器端UpLoadPicture

package com.example.girdviewtest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.SimpleAdapter;
import android.widget.SimpleAdapter.ViewBinder;
import android.widget.Toast;
import android.os.Build;
import android.provider.MediaStore;

import java.io.DataOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import sun.geoffery.uploadpic.NetUtil;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

private GridView gridView1; //网格显示缩略图
private Button buttonPublish; //发布按钮
private final int IMAGE_OPEN = 1; //打开图片标记
private String pathImage; //选择图片路径
private Bitmap bmp; //导入临时图片
private ArrayList<HashMap<String, Object>> imageItem;
private SimpleAdapter simpleAdapter; //适配器

private String imgUrl = "http://59.78.93.208:9095/UpLoadPicture";
private Context mContext;
private String resultStr = "";
List<String> list = new ArrayList<String>();


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* 防止键盘挡住输入框
* 不希望遮挡设置activity属性 android:windowSoftInputMode="adjustPan"
* 希望动态调整高度 android:windowSoftInputMode="adjustResize"
*/
getWindow().setSoftInputMode(WindowManager.LayoutParams.
SOFT_INPUT_ADJUST_PAN);
//锁定屏幕
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.activity_main);
//获取控件对象
gridView1 = (GridView) findViewById(R.id.gridView1);
buttonPublish=(Button) findViewById(R.id.button1);
buttonPublish.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(uploadImageRunnable).start();
}
});

/*
* 载入默认图片添加图片加号
* 通过适配器实现
* SimpleAdapter参数imageItem为数据源 R.layout.griditem_addpic为布局
*/
bmp = BitmapFactory.decodeResource(getResources(), R.drawable.gridview_addpic); //加号
imageItem = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("itemImage", bmp);
imageItem.add(map);
simpleAdapter = new SimpleAdapter(this,
imageItem, R.layout.griditem_addpic,
new String[] { "itemImage"}, new int[] { R.id.imageView1});
/*
* HashMap载入bmp图片在GridView中不显示,但是如果载入资源ID能显示 如
* map.put("itemImage", R.drawable.img);
* 解决方法:
* 1.自定义继承BaseAdapter实现
* 2.ViewBinder()接口实现
* 参考 http://blog.csdn.net/admin_/article/details/7257901
*/
simpleAdapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
// TODO Auto-generated method stub
if(view instanceof ImageView && data instanceof Bitmap){
ImageView i = (ImageView)view;
i.setImageBitmap((Bitmap) data);
return true;
}
return false;
}
});
gridView1.setAdapter(simpleAdapter);

/*
* 监听GridView点击事件
* 报错:该函数必须抽象方法 故需要手动导入import android.view.View;
*/
gridView1.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
if( imageItem.size() == 10) { //第一张为默认图片
Toast.makeText(MainActivity.this, "图片数9张已满", Toast.LENGTH_SHORT).show();
}
else if(position == 0) { //点击图片位置为+ 0对应0张图片
Toast.makeText(MainActivity.this, "添加图片", Toast.LENGTH_SHORT).show();
//选择图片
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, IMAGE_OPEN);
//通过onResume()刷新数据
}
else {
dialog(position);
//Toast.makeText(MainActivity.this, "点击第" + (position + 1) + " 号图片",
// Toast.LENGTH_SHORT).show();
}

}
});
}

//获取图片路径 响应startActivityForResult
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//打开图片
if(resultCode==RESULT_OK && requestCode==IMAGE_OPEN) {
Uri uri = data.getData();
if (!TextUtils.isEmpty(uri.getAuthority())) {
//查询选择图片
Cursor cursor = getContentResolver().query(
uri,
new String[] { MediaStore.Images.Media.DATA },
null,
null,
null);
//返回 没找到选择图片
if (null == cursor) {
return;
}
//光标移动至开头 获取图片路径
cursor.moveToFirst();
pathImage = cursor.getString(cursor
.getColumnIndex(MediaStore.Images.Media.DATA));
}
} //end if 打开图片
}

//刷新图片
@Override
protected void onResume() {
super.onResume();
if(!TextUtils.isEmpty(pathImage)){
Bitmap addbmp=BitmapFactory.decodeFile(pathImage);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("itemImage", addbmp);
imageItem.add(map);
simpleAdapter = new SimpleAdapter(this,
imageItem, R.layout.griditem_addpic,
new String[] { "itemImage"}, new int[] { R.id.imageView1});
simpleAdapter.setViewBinder(new ViewBinder() {
@Override
public boolean setViewValue(View view, Object data,
String textRepresentation) {
// TODO Auto-generated method stub
if(view instanceof ImageView && data instanceof Bitmap){
ImageView i = (ImageView)view;
i.setImageBitmap((Bitmap) data);
return true;
}
return false;
}
});
gridView1.setAdapter(simpleAdapter);
simpleAdapter.notifyDataSetChanged();
//刷新后释放防止手机休眠后自动添加
list.add(pathImage);
pathImage = null;
}
}

/*
* Dialog对话框提示用户删除操作
* position为删除图片位置
*/
protected void dialog(final int position) {
AlertDialog.Builder builder = new Builder(MainActivity.this);
builder.setMessage("确认移除已添加图片吗?");
builder.setTitle("提示");
builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
imageItem.remove(position);
simpleAdapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}


Runnable uploadImageRunnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i <list.size(); i++) {
if (TextUtils.isEmpty(imgUrl)) {
Toast.makeText(mContext, "还没有设置上传服务器的路径!", Toast.LENGTH_SHORT).show();
return;
}

Map<String, String> textParams = new HashMap<String, String>();
Map<String, File> fileparams = new HashMap<String, File>();

try {
// 创建一个URL对象
imgUrl="http://59.78.93.208:9095/UpLoadPicture?num="+i;
URL url = new URL(imgUrl);
textParams = new HashMap<String, String>();
fileparams = new HashMap<String, File>();
// 要上传的图片文件
pathImage=list.get(i);
File file = new File(pathImage);
fileparams.put("image", file);
// 利用HttpURLConnection对象从网络中获取网页数据
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置连接超时(记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操作)
conn.setConnectTimeout(5000);
// 设置允许输出(发送POST请求必须设置允许输出)
conn.setDoOutput(true);
// 设置使用POST的方式发送
conn.setRequestMethod("POST");
// 设置不使用缓存(容易出现问题)
conn.setUseCaches(false);
// 在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成html文件头
conn.setRequestProperty("ser-Agent", "Fiddler");
// 设置contentType
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + NetUtil.BOUNDARY);
OutputStream os = conn.getOutputStream();
DataOutputStream ds = new DataOutputStream(os);
NetUtil.writeStringParams(textParams, ds);
NetUtil.writeFileParams(fileparams, ds);
NetUtil.paramsEnd(ds);
// 对文件流操作完,要记得及时关闭
os.close();
// 服务器返回的响应吗
int code = conn.getResponseCode(); // 从Internet获取网页,发送请求,将网页以流的形式读回来
// 对响应码进行判断
if (code == 200) {// 返回的响应码200,是成功
// 得到网络返回的输入流
InputStream is = conn.getInputStream();
resultStr = NetUtil.readString(is);
} else {
Toast.makeText(mContext, "请求URL失败!", Toast.LENGTH_SHORT).show();
}

} catch (Exception e) {
e.printStackTrace();
}
//Toast.makeText(mContext, "发送成功", Toast.LENGTH_SHORT).show();
//handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
}
};

Handler handler = new Handler(new Handler.Callback() {

@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case 0:
//pd.dismiss();

try {
JSONObject jsonObject = new JSONObject(resultStr);
// 服务端以字符串“1”作为操作成功标记
if (jsonObject.optString("status").equals("1")) {

// 用于拼接发布说说时用到的图片路径
// 服务端返回的JsonObject对象中提取到图片的网络URL路径
String imageUrl = jsonObject.optString("imageUrl");
// 获取缓存中的图片路径
Toast.makeText(mContext, imageUrl, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, jsonObject.optString("statusMessage"), Toast.LENGTH_SHORT).show();
}

} catch (JSONException e) {
e.printStackTrace();
}
break;
default:
break;
}
return false;
}
});

}

以上是关于android 批量上传图片的主要内容,如果未能解决你的问题,请参考以下文章

android批量文件上传(android批量图片上传)

android 批量上传图片

Android - 应用程序启动时片段 onCreate 崩溃

android之使用GridView+仿微信图片上传功能(附源代码)

Android高仿微信图片选择上传工具

摒弃FORM表单上传图片,异步批量上传照片