android调用webservice实现图片上传

下面是相应的代码

1.android调用webservice使用ksoap,需要引入ksoap2-android-assembly-2.6.4-jar-with-dependencies.jar

2.AndroidManifest.xml中需添加相应的权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>  
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>  
<uses-permission android:name="android.permission.INTERNET"/>
android端代码:

package com.example.camera;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

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.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class MainActivity extends Activity {
	TextView tv = null;
	String fileName = "/sdcard/myImage/my.jpg"; //图片保存sd地址
	String namespace = "http://webservice.service.com";  // 命名空间  
    String url = "http://192.168.200.19:8080/Web/webservices/Portal";  //对应的url
    String methodName = "uploadImage"; //webservice方法
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		tv = (TextView)findViewById(R.id.textView);
		
		//启用相机按钮
		Button button = (Button) findViewById(R.id.button);
		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				startActivityForResult(intent, 1);
			}
		});
		
		//保存图片到服务器按钮(通过webservice实现)
		Button saveButton = (Button) findViewById(R.id.savePic);
		saveButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				testUpload();
			}
		});
	}

	/**
	 * 拍照完成后,回掉的方法
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
				Log.v("TestFile",
				"SD card is not avaiable/writeable right now.");
				return;
			}

			Bundle bundle = data.getExtras();
			Bitmap bitmap = (Bitmap) bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式
			FileOutputStream b = null;
			File file = new File("/sdcard/myImage/");
			file.mkdirs();// 创建文件夹
			try {
				b = new FileOutputStream(fileName);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					b.flush();
					b.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);// 将图片显示在ImageView里
		}
	}
	
	/**
	 * 图片上传方法
	 * 
	 * 1.把图片信息通过Base64转换成字符串
	 * 2.调用connectWebService方法实现上传
	 */
	private void testUpload(){  
        try{    
            FileInputStream fis = new FileInputStream(fileName);  
            ByteArrayOutputStream baos = new ByteArrayOutputStream();  
            byte[] buffer = new byte[1024];  
            int count = 0;  
            while((count = fis.read(buffer)) >= 0){  
                baos.write(buffer, 0, count);  
            }  
            String uploadBuffer = new String(Base64.encode(baos.toByteArray()));  //进行Base64编码  
            connectWebService(uploadBuffer);   
            Log.i("connectWebService", "start");  
            fis.close();  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
    } 
	
	/**
	 * 通过webservice实现图片上传
	 * 
	 * @param imageBuffer
	 */
	private void connectWebService(String imageBuffer) {  
        //以下就是 调用过程了,不明白的话 请看相关webservice文档     
        SoapObject soapObject = new SoapObject(namespace, methodName);      
        soapObject.addProperty("filename", "my.jpg");  //参数1   图片名  
        soapObject.addProperty("image", imageBuffer);   //参数2  图片字符串  
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(  
                SoapEnvelope.VER11);  
        envelope.dotNet = false;  
        envelope.setOutputSoapObject(soapObject);  
        HttpTransportSE httpTranstation = new HttpTransportSE(url);  
        try {  
            httpTranstation.call(namespace, envelope);  
            Object result = envelope.getResponse();  
            Log.i("connectWebService", result.toString());  
            tv.setText(result.toString());
        } catch (Exception e) {  
            e.printStackTrace();
            tv.setText(e.getStackTrace().toString());
        }  
    }  

}
服务端代码:

public String uploadImage(String filename, String image) { 
	    FileOutputStream fos = null;  
	    try{  
	        String toDir = "D:\\work\\image";   //存储路径  
	        byte[] buffer = new BASE64Decoder().decodeBuffer(image);   //对android传过来的图片字符串进行解码   
	        File destDir = new File(toDir);    
	        if(!destDir.exists()) {
	        	destDir.mkdir();  
	        }
	        fos = new FileOutputStream(new File(destDir,filename));   //保存图片  
	        fos.write(buffer);  
	        fos.flush();  
	        fos.close();  
	        return "上传图片成功!" + "图片路径为:" + toDir;  
	    }catch (Exception e){  
	        e.printStackTrace();  
	    }  
	    return "上传图片失败!";  
	}
这里图片过大可能会出现错误,压缩处理一下过大的图片:

import android.graphics.Bitmap;
import android.graphics.Matrix;

public class ZoomBitmap {

public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
double newHeight) {
// 获取这个图片的宽和高
float width = bgimage.getWidth();
float height = bgimage.getHeight();
// 创建操作图片用的matrix对象
Matrix matrix = new Matrix();
// 计算宽高缩放率
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// 缩放图片动作
matrix.postScale(scaleWidth, scaleHeight);
Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
(int) height, matrix, true);
return bitmap;
}








  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值