package com.image.upload; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Calendar; import org.kobjects.base64.Base64; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.Toast; public class ImageUploadActivity extendsActivity{ privateButton upload; privateImageView image; privatestatic final String NAMESPACE ="[color=#0066cc]http://tempuri.org/[/color]"; //[color=#0066cc]http://tempuri.org/[/color] // WebService地址 privatestatic String URL ="[color=#0066cc]http://192.168.2.102:8086/WebService1.asmx?WSDL[/color]"; privatestatic final String METHOD_NAME ="FileUploadImage"; privatestatic String SOAP_ACTION ="[color=#0066cc]http://tempuri.org/FileUploadImage[/color]"; privatestatic String PhotoName=""; privatefinal String IMAGE_TYPE ="image/*"; privatefinal int IMAGE_CODE = 0; EditText text; /** Called when the activity is first created. */ @Override publicvoid onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // final EditText text=(EditText)this.findViewById(R.id.text); Button makePhoto; Button select; image = (ImageView)this.findViewById(R.id.image); select=(Button)this.findViewById(R.id.select); makePhoto=(Button)this.findViewById(R.id.makephoto); upload=(Button)this.findViewById(R.id.upload); select.setOnClickListener(newButton.OnClickListener() { @Override publicvoid onClick(View v) { // TODO Auto-generated method stub Intent getAlbum =new Intent(Intent.ACTION_GET_CONTENT); getAlbum.setType(IMAGE_TYPE); startActivityForResult(getAlbum, IMAGE_CODE); } }); makePhoto.setOnClickListener(newButton.OnClickListener() { @Override publicvoid onClick(View v) { // TODO Auto-generated method stub Calendar ca = Calendar.getInstance(); intyear = ca.get(Calendar.YEAR);//获取年份 intmonth=ca.get(Calendar.MONTH);//获取月份 intday=ca.get(Calendar.DATE);//获取日 intminute=ca.get(Calendar.MINUTE);//分 inthour=ca.get(Calendar.HOUR);//小时 intsecond=ca.get(Calendar.SECOND);//秒 String fileName=String.valueOf(year)+String.valueOf(month)+String.valueOf(day)+String.valueOf(hour)+String.valueOf(minute)+String.valueOf(second); PhotoName="/mnt/sdcard/"+String.valueOf(year)+String.valueOf(month)+String.valueOf(day)+String.valueOf(hour)+String.valueOf(minute)+String.valueOf(second)+".jpg"; Intent intent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE); intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(newFile(Environment .getExternalStorageDirectory(),fileName+".jpg"))); startActivityForResult(intent,1); } }); upload.setOnClickListener(newButton.OnClickListener(){ @Override publicvoid onClick(View v) { // TODO Auto-generated method stub String str = testUpload(); booleanisSussess; try{ isSussess = connectWebService(str); if(isSussess==true) { Toast.makeText(getBaseContext(),"图片上传成功!", Toast.LENGTH_LONG).show(); } else{ Toast.makeText(getBaseContext(),"图片上传失败!", Toast.LENGTH_LONG).show(); } }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } publicString testUpload(){ try{ String srcUrl =PhotoName;//"/mnt/sdcard/"; //路径 //String fileName = PhotoName+".jpg"; //文件名 FileInputStream fis =new FileInputStream(srcUrl); ByteArrayOutputStream baos =new ByteArrayOutputStream(); byte[] buffer =new byte[8192]; intcount = 0; while((count = fis.read(buffer)) >=0){ baos.write(buffer,0, count); } String uploadBuffer =new String(Base64.encode(baos.toByteArray())); //进行Base64编码 returnuploadBuffer; }catch(Exception e){ e.printStackTrace(); } //return soapObject; returnnull; } privateboolean connectWebService(String uploadBuffer)throws IOException { SoapObject soapObject =new SoapObject(NAMESPACE, METHOD_NAME); soapObject.addProperty("title",""); soapObject.addProperty("contect",""); soapObject.addProperty("bytestr", uploadBuffer); //参数2 图片字符串 SoapSerializationEnvelope envelope =new SoapSerializationEnvelope(SoapEnvelope.VER10); envelope.setOutputSoapObject(soapObject); envelope.bodyOut = soapObject; envelope.dotNet =true; envelope.encodingStyle = SoapSerializationEnvelope.ENC; HttpTransportSE httpTranstation =new HttpTransportSE(URL); try{ httpTranstation.call(SOAP_ACTION, envelope); returntrue; }catch (Exception e) { e.printStackTrace(); returnfalse; } } }); } protectedvoid onActivityResult(intrequestCode, intresultCode, Intent data){ if(resultCode != RESULT_OK) { //此处的 RESULT_OK 是系统自定义得一个常量 return; } if(requestCode == IMAGE_CODE) { try{ Uri selectedImage = data.getData(); String[] filePathColumn = { MediaStore.Images.Media.DATA }; Cursor cursor = getContentResolver().query(selectedImage, filePathColumn,null, null,null); cursor.moveToFirst(); intcolumnIndex = cursor.getColumnIndex(filePathColumn[0]); String picturePath = cursor.getString(columnIndex); // text.setText(picturePath); PhotoName=picturePath; cursor.close(); image.setImageBitmap(BitmapFactory.decodeFile(picturePath)); }catch (Exception e) { // TODO: handle exception e.printStackTrace(); } } } } 复制代码 权限添加: [font=Courier New]<uses-permission android:name="android.permission.INTERNET"[/font]></uses-permission> <uses-permission android:name="android.permission.CAMERA"/> <uses-feature android:name="android.hardware.camera"/> <uses-feature android:name="android.hardware.camera.autofocus"android:required="false"/> 复制代码 main.xml: <?xml version="1.0"encoding="utf-8"?> <LinearLayout xmlns:android="[color=#0066cc]http://schemas.android.com/apk/res/android[/color]" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" android:background="#87CEFA"> <Button android:id="@+id/makephoto" android:layout_width="94dp" android:layout_height="wrap_content" android:text="拍照"/> <ImageView android:id="@+id/image" android:layout_width="match_parent" android:layout_height="384dp" android:background="#8B8B7A"/> <TableLayout android:id="@+id/tableLayout1" android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow android:id="@+id/tableRow1" android:layout_width="wrap_content" android:layout_height="wrap_content" > <Button android:id="@+id/upload" android:layout_width="95dp" android:layout_height="wrap_content" android:text="上传"/> <Button android:id="@+id/select" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="查看"/> </TableRow> </TableLayout> </LinearLayout> 复制代码 webservice: [font=Courier New]publicstring FileUploadImage(string title, string contect, string bytestr)[/font] { string name =""; string mess =""; if(bytestr == "") { return"失败"; } try { // Random random = new Random(); //string i = random.Next(0, 10000000).ToString(); name = DateTime.Now.Year.ToString() + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Hour + DateTime.Now.Minute + DateTime.Now.Second; bool flag = StringToFile(bytestr, Server.MapPath("image\\") +"" + name + ".jpg"); string filePath ="/image/" + name +".jpg"; MODEL.BusinessInfo mo =new MODEL.BusinessInfo(); //mo.Title = title; // mo.Contents = contect; //mo.Fileds = filePath; BLL.BusinessInfo bll =new BLL.BusinessInfo(); bll.Add(mo); if(flag == true) { return"成功"; } else { return"失败"; } } catch(Exception ex) { mess = ex.Message; } if(mess != "") { returnmess; } else { return"文件上传成功"; } } protectedSystem.Drawing.Image Base64StringToImage(string strbase64) { try { byte[] arr = Convert.FromBase64String(strbase64); MemoryStream ms =new MemoryStream(arr); //Bitmap bmp = new Bitmap(ms); ms.Write(arr,0, arr.Length); System.Drawing.Image image = System.Drawing.Image.FromStream(ms); ms.Close(); returnimage; //return bmp; } catch(Exception ex) { throwex; } } /// <summary> /// 把经过base64编码的字符串保存为文件 /// </summary> /// <param name="base64String">经base64加码后的字符串 </param> /// <param name="fileName">保存文件的路径和文件名 </param> /// <returns>保存文件是否成功 </returns> publicstatic bool StringToFile(string base64String, string fileName) { //string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"/beapp/" + fileName; System.IO.FileStream fs =new System.IO.FileStream(fileName, System.IO.FileMode.Create); System.IO.BinaryWriter bw =new System.IO.BinaryWriter(fs); if(!string.IsNullOrEmpty(base64String) && File.Exists(fileName)) { bw.Write(Convert.FromBase64String(base64String)); } bw.Close(); fs.Close(); returntrue; } 复制代码 转自:http://blog.csdn.net/yu491290710/article/details/7900830