http://blog.163.com/gobby_1110/blog/static/29281715201217253125/
这样的,从Android端用io流读取到要上传的图片,用Base64编码成字节流的字符串,通过调用webservice把该字符串作为参数传到服务器端,服务端解码该字符串,最后保存到相应的路径下。整个上传过程的关键就是 以 字节流的字符串 进行数据传递。下载过程,与上传过程相反,把服务器端和客户端的代码相应的调换。
不罗嗦那么多,上代码。流程是:把Android的sdcard上某张图片 上传到 服务器下images 文件夹下。 注:这只是个demo,没有UI界面,文件路径和文件名都已经写死,运行时,相应改一下就行。
1 。读取Android sdcard上的图片。
1.public void testUpload(){
2. try{
3. String srcUrl = "/sdcard/"; //路径
4. String fileName = "aa.jpg"; //文件名
5. FileInputStream fis = new FileInputStream(srcUrl + fileName);
6. ByteArrayOutputStream baos = new ByteArrayOutputStream();
7. byte[] buffer = new byte[1024];
8. int count = 0;
9. while((count = fis.read(buffer)) >= 0){
10. baos.write(buffer, 0, count);
11. }
12.
13. String uploadBuffer = new String(Base64.encode(baos.toByteArray())); //进行Base64编码
14. String methodName = "uploadImage";
15. connectWebService(methodName,fileName, uploadBuffer); //调用webservice
16. Log.i("connectWebService", "start");
17.
18. fis.close();
19.
20. }catch(Exception e){
21. e.printStackTrace();
22. }
23. }
connectWebService()方法:
1.//使用 ksoap2 调用webservice
2. private boolean connectWebService(String methodName,String fileName, String imageBuffer) {
3. String namespace = "http://134.192.44.105:8080/SSH2/service/IService"; // 命名空间,即服务器端得接口,注:后缀没加 .wsdl,
4. //服务器端我是用x-fire实现webservice接口的
5. String url = "http://134.192.44.105:8080/SSH2/service/IService"; //对应的url
6.
7. //以下就是 调用过程了,不明白的话 请看相关webservice文档
8. SoapObject soapObject = new SoapObject(namespace, methodName);
9. soapObject.addProperty("filename", fileName); //参数1 图片名
10. soapObject.addProperty("image", imageBuffer); //参数2 图片字符串
11. SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
12. SoapEnvelope.VER10);
13. envelope.dotNet = false;
14. envelope.setOutputSoapObject(soapObject);
15. HttpTransportSE httpTranstation = new HttpTransportSE(url);
16. try {
17. httpTranstation.call(namespace, envelope);
18. Object result = envelope.getResponse();
19. Log.i("connectWebService", result.toString());
20. } catch (Exception e) {
21. e.printStackTrace();
22. }
23.
24. return false;
25. }
2。 服务器端的webservice代码 :
1.public String uploadImage(String filename, String image) {
2. FileOutputStream fos = null;
3. try{
4. String toDir = "C:\\Program Files\\Tomcat 6.0\\webapps\\SSH2\\images"; //存储路径
5.
6. byte[] buffer = new BASE64Decoder().decodeBuffer(image); //对Android传过来的图片字符串进行解码
7. File destDir = new File(toDir);
8. if(!destDir.exists()) destDir.mkdir();
9. fos = new FileOutputStream(new File(destDir,filename)); //保存图片
10. fos.write(buffer);
11. fos.flush();
12. fos.close();
13. return "上传图片成功!" + "图片路径为:" + toDir;
14. }catch (Exception e){
15. e.printStackTrace();
16. }
17. return "上传图片失败!";
18.}
对Android 端进行 单元测试调用testUpload()方法,如果你看到绿条的话,说明调用成功!在服务器下,就可以看到你上传的图片了。
当然,这个demo很简陋,没有漂亮UI什么的,但是这是 Android端调用webservice进行上传图片的过程。从服务器下载到Android端,道理亦然。欢迎大家交流学习。
原文链接:http://www.linuxidc.com/Linux/2011-08/41161p2.htm