android之調用webservice 實現圖片上傳

最近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;
}
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端,道理亦然。歡迎大家交流學習。。。。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章