最近做項目需要一個拍照後,將圖片上傳到伺服器的功能,並且伺服器是cs的webservice寫的,通常我們調用webservcie通訊都是傳遞xml或者json格式的字串。從來沒傳過圖片這樣的檔案。百度了很多方法,最後使用了從android端用io流讀取到要上傳的圖片,用Base64編碼成位元組流的字串,通過調用webservice把該字串作為參數傳到伺服器端,服務端解碼該字串,最後儲存到相應的路徑下。整個上傳過程的關鍵就是
以 位元組流的字串 進行資料傳遞。下載過程,與上傳過程相反,把伺服器端和用戶端的代碼相應的調換的方法。
以下為找到的文章所述:
原文地址:http://www.cnblogs.com/top5/archive/2012/02/16/2354517.html
不羅嗦那麼多,上代碼。流程是:把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端,道理亦然。歡迎大家交流學習。。。。