在Android中通過XFire WebService遠程上傳以及下載圖片
有時我們可以看到,圖片往往被提交到服務器端,這里我通過XFire框架來實現遠程上傳以及下載圖片的功能。
首先我們來看看從服務器端下載圖片的功能:
我用的是KSOAP框架,我之前的文章有講述過。在這里不要多說,貼上代碼。
首先我們看看Acitivity中的代碼:
package com.net.connect.app;
import java.io.File;
import java.io.FileInputStream;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.base.encry.decry.app.Base64;
import com.base.file.util.FileOperate;
import com.cn.blogs.ksoap.app.MyWebServiceHelper;
public class UpAndDownPicFileActivity extends Activity {
ImageView imageView;
public static final String filename = "xfire.png";
public static final String fileDir = "/sdcard/xmlfile/";
public MyWebServiceHelper myWebServiceHelper = new MyWebServiceHelper();
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.upanddownpic);
imageView = (ImageView) this.findViewById(R.id.imageView1);
// Bitmap
// bitmap=BitmapFactory.decodeFile("/sdcard/xmlfile/"+"xfire.png");
// imageView.setImageBitmap(bitmap);
Button downButton = (Button) findViewById(R.id.downbutton);
downButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
myWebServiceHelper.getTranferFileString(filename);
// 收到服務器端發送過來的圖片,然后顯現在圖片框中
Bitmap bitmap = BitmapFactory.decodeFile(fileDir + filename);
imageView.setImageBitmap(bitmap);
}
});
Button upButton = (Button) findViewById(R.id.upbutton);
upButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String fileContent = "";
FileOperate.OpenOrCreateFile(filename);
fileContent = FileOperate.bin2XmlString(fileDir+filename);
// Toast.makeText(UpAndDownPicFileActivity.this, fileContent, Toast.LENGTH_LONG).show();
String result=myWebServiceHelper.upToServerOfFileStringWithEncode(filename,
fileContent);
try {
Thread.currentThread().sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(UpAndDownPicFileActivity.this, result, Toast.LENGTH_LONG).show();
// 收到服務器端發送過來的圖片,然后顯現在圖片框中
//imageView.setImageBitmap(null);
}
});
}
}
分別實現了遠程上傳和下載圖片的功能。它的處理類集中在MyWebServiceHelper,它實現了遠程獲取和上傳的細節功能。
這個功能都是通過KSOAP框架實現的。下面貼上它的代碼,如下所示:
// WSDL文檔中的命名空間
private static final String targetNameSpace = "http://android.googlepages.com/";
// WSDL文檔中的URL
private static final String WSDL = "http://10.10.178.71:8888/WSDLApp/services/MyService";
// 需要調用的方法名(獲得Myervices中的helloWorld方法)
private static final String getHelloworld = "helloWorld";
//需要調用的方法名(獲得Myervices中的login方法)
private static final String getLogin="login";
//獲取加密圖片的字符串
private static final String getTranferFileStringWithEncode="tranferFileStringWithEncode";
//獲取加密圖片的字符串
private static final String upToServerOfFileContent="fetchFileStringWithEncode";
public String getTranferFileString(String filename) {
String fileContent = "";
SoapObject soapObject = new SoapObject(targetNameSpace,getTranferFileStringWithEncode);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = false;
envelope.setOutputSoapObject(soapObject);
HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
try {
httpTranstation.call(targetNameSpace + getTranferFileStringWithEncode, envelope);
SoapObject result = (SoapObject ) envelope.bodyIn;//getResponse();
fileContent=(String) result.getProperty(0).toString();
//String strFile="downfromserive"+Math.random()+".png";
FileOperate.OpenOrCreateFile(filename);
FileOperate.xmlString2Bin(fileContent, new File(filename));
// 也可以通過下面方式獲得str
// SoapPrimitive result = (SoapPrimitive ) envelope.getResponse();
// str=result.toString();
// 直指value字符串值
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return fileContent;
}
public String upToServerOfFileStringWithEncode(String filename,String fileContent) {
String str = "";
SoapObject soapObject = new SoapObject(targetNameSpace,upToServerOfFileContent);
soapObject.addProperty("filename", filename);
soapObject.addProperty("fileContent", fileContent);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = false;
envelope.setOutputSoapObject(soapObject);
HttpTransportSE httpTranstation=new HttpTransportSE(WSDL);
try {
httpTranstation.call(targetNameSpace + upToServerOfFileContent, envelope);
SoapObject result = (SoapObject ) envelope.bodyIn;//getResponse();
str=(String) result.getProperty(0).toString();
//返回上傳成功0,1標志位
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.getMessage();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.getMessage();
}
return str;
}
在第二個函數中有:
SoapObject soapObject = new SoapObject(targetNameSpace,upToServerOfFileContent);
soapObject.addProperty("filename", filename);
soapObject.addProperty("fileContent", fileContent);
這個是android客戶端傳送服務器端的參數參數。
而里面有個FileOperate.java類,這個類負責對文件操作。我封裝在這個類中,方便集中處理以及調用。
下面貼上代碼。如下所示:
package com.base.file.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.base.encry.decry.app.Base64;
public class FileOperate {
//在SD卡中創建文件
public static void OpenOrCreateFile(String filename){
// 獲取擴展SD卡設備狀態
String sDStateString = android.os.Environment
.getExternalStorageState();
if (sDStateString.equals(android.os.Environment.MEDIA_MOUNTED)) {
// String strFile="downfromserive"+Math.random()+".png";
// 獲取擴展存儲設備的文件目錄
File SDFile = android.os.Environment
.getExternalStorageDirectory();
File destDir = new File("/sdcard/xmlfile");
// File destDir = new File(SDFile.getAbsolutePath() +
// destDirStr);
if (!destDir.exists())
destDir.mkdir();
// Toast.makeText(SDCardTest., text, duration)
// 打開文件
File myFile = new File(destDir + File.separator + filename);
// 判斷是否存在,不存在則創建
if (!myFile.exists()) {
try {
myFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//刪除指定文件,比如臨時文件
public static void removeFile(String filename){
if(new File(filename).exists())
new File(filename).delete();
}
//解密,并將內容寫入至指定文件中
public static boolean xmlString2Bin(String base64String, File file) {
byte[] data;
FileOutputStream output = null;
boolean ret = false;
try {
data = Base64.decode(base64String);
output = new FileOutputStream(file);
output.write(data);
output.close();
ret = true;
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
//將文件內容加密
public static String bin2XmlString(String filename) {
byte[] data = null;
FileInputStream input = null;
String ret = null;
int n;
try {
data = new byte[(int) new File(filename).length()];
input = new FileInputStream(new File(filename));
n = input.read(data);//這個就是一個文件讀取過程。沒有寫while,一次性讀完
input.close();
ret = new String(Base64.encode(data));
} catch (Exception e) {
e.printStackTrace();
}
return ret;
}
}
當然,我們還在看看這個Activity.java中的布局文件。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="@string/hello" />
<Button android:id="@+id/downbutton" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="下載" />
<Button android:id="@+id/upbutton" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="上傳" />
<ImageView android:id="@+id/imageView1" android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
而服務器端用的是XFire框架,這在之前的文章中講過。不必多說。
看下面的代碼:
在AccountImp.java中實現IAccount.java方法。
public String tranferFileStringWithEncode() {
// TODO Auto-generated method stub
return FileOperate.bin2XmlString("E://Workspaces//workspace//WSDLApp//"+"girl.png");
}
public String fetchFileStringWithEncode(String filename, String fileContent) {
// TODO Auto-generated method stub
//創建該新文件,并返回成功
try {
//打開并創建文件
FileOperate.OpenOrCreateFile(filename);
String pathFile="E://Workspaces//workspace//WSDLApp";
//解密,并將內容添加至該文件中
FileOperate.xmlString2Bin(fileContent, new File("E://Workspaces//workspace//WSDLApp//xfire.png"));
return "上傳成功";
} catch (Exception e) {
// TODO: handle exception
return "上傳失敗";
}
}
IAccount.java
//將 POJO 發布成 Web 服務:有兩種方法,接口和實現類是其中之一
public interface IAccount {
public int account(int x,int y);
public String helloWorld(String str);
//訪問mysql數據庫
public int login(String username,String password);
//傳送圖片字符串
public String tranferFileStringWithEncode();
//接收遠程傳送過來的圖片字符串
public String fetchFileStringWithEncode(String username,String filename);
}
而這個XFIRE要在web.xml中注冊.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>XFireServlet</servlet-name>
<servlet-class>org.codehaus.xfire.transport.http.XFireConfigurableServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>XFireServlet</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
這樣Web服務就用去查找services目錄下。所以還要在WebServices目錄下(在該服務器端要目錄下)創建
services.xml文件。如下所示:
<!-- 服務一:簡單計算,直接輸出 -->
<service>
<name>MyService</name>
<serviceClass>test.IAccount</serviceClass>
<implementationClass>test.AccountImp</implementationClass>
<mce:style><!--
wrapped
--></mce:style><style mce_bogus="1">wrapped</style>
<use>literal</use>
<scope>application</scope>
<namespace>http://android.googlepages.com/</namespace>
</service>
最終實現效果如下所示:
點擊上傳按鈕
點擊下載按鈕
來自:http://blog.csdn.net/haha_mingg/article/details/6347588
本文由用戶 fmms 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!