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

android之调用webservice 实现图片上传

2016-03-08 00:00 597 查看
android客户端的图片上传和下载,就是调用服务器的webservice接口,实现从android上传图片到服务器,然后从服务器下载图片到android客户端。

通常,我们调用webservice,就是服务器和客户端(浏览器,android手机端等)之间的通信,其通信一般是传 xml或json格式的字符串。对,就只能是字符串。

我的思路是这样的,从android端用io流读取到要上传的图片,用Base64编码成字节流的字符串,通过调用webservice把该字符串作为参数传到服务器端,服务端解码该字符串,最后保存到相应的路径下。整个上传过程的关键就是 以 字节流的字符串 进行数据传递。下载过程,与上传过程相反,把服务器端和客户端的代码相应的调换。

不罗嗦那么多,上代码。流程是:把android的sdcard上某张图片 上传到 服务器下images 文件夹下。

注:这只是个demo,没有UI界面,文件路径和文件名都已经写死,运行时,相应改一下就行。

1 。读取android sdcard上的图片。

public void testUpload(){

try{

String srcUrl = "/sdcard/"; //路径

String fileName = "aa.jpg"; //文件名

FileInputStream fis = new FileInputStream(srcUrl + 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编码

String methodName = "uploadImage";

connectWebService(methodName,fileName, uploadBuffer); //调用webservice

Log.i("connectWebService", "start");

fis.close();

}catch(Exception e){

e.printStackTrace();

}

}

connectWebService()方法:

//使用 ksoap2 调用webservice

private boolean connectWebService(String methodName,String fileName, String imageBuffer) {

String namespace = "http://134.192.44.105:8080/SSH2/service/IService"; // 命名空间,即服务器端得接口,注:后缀没加 .wsdl,

//服务器端我是用x-fire实现webservice接口的

String url = "http://134.192.44.105:8080/SSH2/service/IService"; //对应的url

//以下就是 调用过程了,不明白的话 请看相关webservice文档

SoapObject soapObject = new SoapObject(namespace, methodName);

soapObject.addProperty("filename", fileName); //参数1 图片名

soapObject.addProperty("image", imageBuffer); //参数2 图片字符串

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(

SoapEnvelope.VER10);

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());

} catch (Exception e) {

e.printStackTrace();

}

return false;

}

2。 服务器端的webservice代码 :

public String uploadImage(String filename, String image) {

FileOutputStream fos = null;

try{

String toDir = "C:\\Program Files\\Tomcat 6.0\\webapps\\SSH2\\images"; //存储路径

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 "上传图片失败!";

}

对android 端进行 单元测试调用testUpload()方法,如果你看到绿条的话,说明调用成功!在服务器下,就可以看到你上传的图片了。。。。

当然,这个demo很简陋,没有漂亮UI什么的,但是这是 android端调用webservice进行上传图片的过程。从服务器下载到android端,道理亦然。欢迎大家交流学习。。。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: