最近boss要求做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;
- }