您的位置:首页 > 移动开发 > Android开发

Android_本地上传照片文件

2011-10-09 14:25 281 查看
本地上传照片文件

一.知识点

1.遍历SD卡中某一路径下指定类型的图片

2.上传图片

二.代码解析public class LocationPhoto extends Activity implements Runnable {

private Bundle bundle;

private Intent intent;

private String type = null;

private String dianya = null;

private String name = null;

Gallery g = null;

Button but1 = null;// 选择按钮

Button but2 = null;// 删除按钮

Button but3 = null;// 上传按钮

TextView text1 = null;// 命名Text

EditText edit1 = null;// 命名Edit

List<String> it = null;// 遍历符合条件的列表

List<String> seList = new ArrayList<String>();// 已选择列表

public String actionUrl = null;

public String dqPhoto = null;

public ProgressDialog myDialog=null;

private final String SD_PATH = android.os.Environment

.getExternalStorageDirectory().getAbsolutePath();

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.location_photo);

intent = getIntent();

bundle = intent.getExtras();

int num = bundle.getInt("selectType");

type = new TypeDianyaOptions().getSelectType(num);

dianya = new TypeDianyaOptions().getSelectDianYa(num);

g = (Gallery) findViewById(R.id.mygallery);

but1 = (Button) findViewById(R.id.but1);

but2 = (Button) findViewById(R.id.but2);

but3 = (Button) findViewById(R.id.but3);

text1 = (TextView) findViewById(R.id.newNameText);

edit1 = (EditText) findViewById(R.id.nameEdit);

g.setAdapter(new ImageAdapter(this, getSD()));

g.setOnItemClickListener(new OnItemClickListener() {

public void onItemClick(AdapterView<?> parent, View v,

int position, long id) {

dqPhoto = it.get(position);

Toast.makeText(LocationPhoto.this,

"序列:" + (position + 1) + "\n路径:" + it.get(position),

Toast.LENGTH_LONG).show();

}

});

//选择功能

but1.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

if (dqPhoto == null) {

Toast.makeText(LocationPhoto.this, "点击锁定图片",

Toast.LENGTH_LONG).show();

} else if (seList.contains(dqPhoto)) {

dqPhoto = null;

Toast.makeText(LocationPhoto.this, "图片已在选择列",

Toast.LENGTH_LONG).show();

} else {

seList.add(dqPhoto);

dqPhoto = null;

Toast.makeText(LocationPhoto.this, "选择成功",

Toast.LENGTH_LONG).show();

}

}

});

//删除功能

but2.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

if (dqPhoto == null) {// 未选择图片时

Toast.makeText(LocationPhoto.this, "点击锁定图片",

Toast.LENGTH_LONG).show();

} else if (!seList.contains(dqPhoto)) {

dqPhoto = null;

Toast.makeText(LocationPhoto.this, "图片不在选择列中",

Toast.LENGTH_LONG).show();

} else {

if (seList.remove(dqPhoto)) {

dqPhoto = null;

Toast.makeText(LocationPhoto.this, "图片已从选择列中删除",

Toast.LENGTH_LONG).show();

} else {// 从选择列中删除失败

dqPhoto = null;

Toast.makeText(LocationPhoto.this, "图片删除失败",

Toast.LENGTH_LONG).show();

Toast.makeText(LocationPhoto.this,

"选择的数目:" + seList.size(), Toast.LENGTH_LONG)

.show();

}

}

}

});

//上传功能

but3.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

name = edit1.getText().toString();

actionUrl = "http://124.128.199.98:8090/JNDLS/uploadImage?type="

+ type + "&dianya=" + dianya + "&name=" + name;

if (seList != null && seList.size() > 0) {

if (name != null && name.length() > 0) {

myDialog=ProgressDialog.show(LocationPhoto.this, "请稍等", "正在执行上传请求中...");

Thread thread=new Thread(LocationPhoto.this);

thread.start();

} else {

Toast.makeText(LocationPhoto.this, "请填写杆号为图片命名!",

Toast.LENGTH_LONG).show();

}

} else {

Toast.makeText(LocationPhoto.this, "尚未选择上传图片!",

Toast.LENGTH_LONG).show();

}

}

});

}

//遍历SD卡中某一路径下指定类型的图片

private List<String> getSD() {

it = new ArrayList<String>();

File f = new File(SD_PATH + "//" + "jndlzp");

File[] files = f.listFiles();

for (int i = 0; i < files.length; i++) {

File file = files[i];

if (getImageFile(file.getPath()))

it.add(file.getPath());

}

return it;

}

//指定遍历文件类型

private boolean getImageFile(String fName) {

boolean re;

String end = fName

.substring(fName.lastIndexOf(".") + 1, fName.length())

.toLowerCase();

if (end.equals("jpg") || end.equals("gif") || end.equals("png")

|| end.equals("jpeg") || end.equals("bmp")) {

re = true;

} else {

re = false;

}

return re;

}

public class ImageAdapter extends BaseAdapter {

int mGalleryItemBackground;

private Context mContext;

private List<String> lis;

public ImageAdapter(Context c, List<String> li) {

mContext = c;

lis = li;

TypedArray a = obtainStyledAttributes(R.styleable.Gallery);

mGalleryItemBackground = a.getResourceId(

R.styleable.Gallery_android_galleryItemBackground, 0);

a.recycle();

}

public int getCount() {

return lis.size();

}

public Object getItem(int position) {

return position;

}

public long getItemId(int position) {

return position;

}

public View getView(int position, View convertView, ViewGroup parent) {

ImageView i = new ImageView(mContext);

Bitmap bm = BitmapFactory.decodeFile(lis.get(position).toString());

i.setImageBitmap(bm);

i.setScaleType(ImageView.ScaleType.FIT_XY);

i.setLayoutParams(new Gallery.LayoutParams(188, 288));

i.setBackgroundResource(mGalleryItemBackground);

return i;

}

}

public void run() {

// TODO Auto-generated method stub

try {

for (int i = 0; i < seList.size(); i++) {

uploadFile(actionUrl, seList.get(i));

}

handler.sendEmptyMessage(0);

} catch (Exception e) {

showDialog("上传失败!");

}

}

//Handler构建之后,会坚挺传来的信息代码

private Handler handler=new Handler(){

@Override

public void handleMessage(Message msg) {

// TODO Auto-generated method stub

myDialog.dismiss();

seList.clear();

showDialog("上传成功!");

}

};

  public void uploadFile(String actionUrl, String uploadFile) {

String end = "\r\n";

String twoHyphens = "--";

String boundary = "*****";

String nameStr = uploadFile.substring(uploadFile.lastIndexOf("/") + 1,

uploadFile.length());

try {

URL url = new URL(actionUrl);

HttpURLConnection con = (HttpURLConnection) url.openConnection();

/* 允许Input、Output,不使用Cache */

con.setDoInput(true);

con.setDoOutput(true);

con.setUseCaches(false);

/* 设定传送的method=POST */

con.setRequestMethod("POST");

/* setRequestProperty */

con.setRequestProperty("Connection", "Keep-Alive");

con.setRequestProperty("Charset", "UTF-8");

con.setRequestProperty("Content-Type",

"multipart/form-data;boundary=" + boundary);

/* 设定DataOutputStream */

DataOutputStream ds = new DataOutputStream(con.getOutputStream());

ds.writeBytes(twoHyphens + boundary + end);

ds.writeBytes("Content-Disposition: form-data; "

+ "name=\"file1\";filename=\"" + nameStr + "\"" + end);

ds.writeBytes(end);

/* 取得文件的FileInputStream */

FileInputStream fStream = new FileInputStream(uploadFile);

/* 设定每次写入1024bytes */

int bufferSize = 1024;

byte[] buffer = new byte[bufferSize];

int length = -1;

/* 从文件读取数据到缓冲区 */

while ((length = fStream.read(buffer)) != -1) {

/* 将数据写入DataOutputStream中 */

ds.write(buffer, 0, length);

}

ds.writeBytes(end);

ds.writeBytes(twoHyphens + boundary + twoHyphens + end);

/* close streams */

fStream.close();

ds.flush();

/* 取得Response内容 */

InputStream is = con.getInputStream();

int ch;

StringBuffer b = new StringBuffer();

while ((ch = is.read()) != -1) {

b.append((char) ch);

}

/* 关闭DataOutputStream */

ds.close();

} catch (Exception e) {

}

}

public void showDialog(String mess) {

new AlertDialog.Builder(LocationPhoto.this).setTitle("Message")

.setMessage(mess).setNegativeButton("确定",

new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog,

int which) {

}

}).show();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: