標籤:des android style blog http color os io 使用
轉:http://www.cnblogs.com/top5/archive/2012/02/16/2354517.html
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端,道理亦然。歡迎大家交流學習。。。。
android之調用webservice 實現圖片上傳