您的位置:首页 > 移动开发 > Android开发

使用.NET框架、Web service实现Android的文件上传(一)

2015-12-08 10:49 417 查看




上面是上传结果的展示,下面具体讲一下实现过程。

一、Web Service (.NET)

namespace VedioPlayerWebService.service.vedios
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
[SoapDocumentService(RoutingStyle = SoapServiceRoutingStyle.RequestElement)]
public class GetVedios : System.Web.Services.WebService
{
[WebMethod(EnableSession = true, Description = "上传文件")]
public int FileUploadByBase64String(string base64string, string fileName1)
{
try
{
string fileName = "D:\\VedioPlayerWeb\\videos\\" + fileName1;
// 取得文件夹
string dir = fileName.Substring(0, fileName.LastIndexOf("\\"));
//如果不存在文件夹,就创建文件夹
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
byte[] bytes = Convert.FromBase64String(base64string);
MemoryStream memoryStream = new MemoryStream(bytes, 0, bytes.Length);
memoryStream.Write(bytes, 0, bytes.Length);
// 写入文件
File.WriteAllBytes(fileName, memoryStream.ToArray());
if (File.Exists(fileName))
{
FileStream fsSource = new FileStream(fileName, FileMode.Open, FileAccess.Read);
fsSource.Close();
}
//返回数据如果是1,上传成功!
return 1;
}
catch (Exception ex)
{
//返回如果是-1,上传失败
return -1;
}
}

}
}


二、工具类(Android)

1、将要上传的文件转换成经过处理的Base64字符串

/**
*得到经过处理的Base64字符串
* Created by WFZ on 2015/12/7.
*/
public class Base64Util {
public static String getBase64String(String path) {
byte[] byteArray = null;
byteArray = Fileutil.readFileToByteArray(new File(path));
String strBase64 = new String(Base64.encode(byteArray,0));
return strBase64;
}
}


2、读取文件的工具类

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/**
* 读取文件的工具类
* Created by WFZ on 2015/12/7.
*/
public class Fileutil {
public static byte[] readFileToByteArray(File file) {
FileInputStream fileInputStream = null;
ByteArrayOutputStream byteArrayOutputStream = null;
try {
fileInputStream = new FileInputStream(file);
byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bt = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(bt)) != -1) {
byteArrayOutputStream.write(bt, 0, len);
}
return byteArrayOutputStream.toByteArray();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
}


3、上传文件的工具类,这里需要soap的jar包

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

/**
*
* Created by WFZ on 2015/12/7.
*/
public class QueryUploadUtil {
private String filename, base64string;

public QueryUploadUtil(String base64str, String fileName) {
this.filename = fileName;
this.base64string = base64str;
}
// 需要实现Callable的Call方法
public String call(String wsdl,String url) throws Exception {
String str = "上传失败";
// TODO Auto-generated method stub
try {
//创建SoapObject对象,并指定WebService的命名空间和调用的方法名
SoapObject rpc = new SoapObject("http://tempuri.org/",
"FileUploadByBase64String");
//设置WebService方法的参数
rpc.addProperty("base64string", base64string);
rpc.addProperty("fileName1", filename);
//第3步:创建SoapSerializationEnvelope对象,并指定WebService的版本
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
// 设置bodyOut属性
envelope.bodyOut = rpc;
envelope.dotNet = true;
envelope.setOutputSoapObject(rpc);
//创建HttpTransportSE对象,并指定WSDL文档的URL
/**
* 创建WSDL文档有三种方法:
* 在.NET中有三种方式生成WSDL:
* 1.在Web Service的URL后面加上WDSL需求,如下:
*  http://localhost/webExamples/simpleService.asmx?WSDL * 2.使用disco.exe。在命令行中写下如下的命令:
*  disco http://localhost/webExamples/simpleService.asmx *3.使用System.Web.Services.Description命名空间下提供的类
* */
HttpTransportSE ht = new HttpTransportSE(wsdl);
ht.debug = false;
//调用WebService
ht.call(url, envelope);
//使用getResponse方法获得WebService方法的返回结果
String result = String.valueOf(envelope.getResponse());
//这个地方是我自己设置的从webservice返回的结果,“1”表示上传成功。
if (result.toString().equals("1"))
str = "上传成功";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
str = "上传错误";
}
return str;
}
}


三、布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn"
android:layout_width="match_parent"
android:text="上传"
android:layout_height="wrap_content" />
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/tv3"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>


四、MainActivity文件

import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lhgj.wfz.uploadfiles.utils.Base64Util;
import com.lhgj.wfz.uploadfiles.utils.Fileutil;
import com.lhgj.wfz.uploadfiles.utils.QueryUploadUtil;

import java.io.File;

public class MainActivity extends AppCompatActivity {
private TextView tv1 = null;//上传的文件地址
private TextView tv2 = null;//上传的文件名称
private TextView tv3 = null;//上传是否成功提示
private Button btn = null;//上传按钮
private ImageView img = null;//图片
private  String filePath="/data/data/com.lhgj.wfz.uploadfiles/";//手机中文件存储的位置
private String fileName ="temp.jpg";//上传的图片
private String wsdl ="http://192.168.15.4:1122/service/vedios/GetVedios.asmx?WSDL";//WSDL
private String url ="http://192.168.15.4:1122/service/vedios/GetVedios.asmx/FileUploadByBase64String";//与webservice交互的地址

/**
* 由于上传文件是一个耗时操作,需要开一个异步,这里我们使用handle
* */
private Handler handler = new Handler() {
public void handleMessage(android.os.Message msg) {
String string = (String) msg.obj;
Toast.makeText(MainActivity.this, string, Toast.LENGTH_LONG).show();;
tv3.setText(string);
};
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}

/**
* 初始化view
* */
private void initView(){
tv1 = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv3 = (TextView) findViewById(R.id.tv3);
btn = (Button) findViewById(R.id.btn);
img = (ImageView) findViewById(R.id.iv);

//设置显示的图片
byte[] byteArray = null;
byteArray = Fileutil.readFileToByteArray(new File(filePath+fileName));
Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
byteArray.length);
img.setImageBitmap(bitmap);

//设置显示的文本
tv1.setText("文件位置:" + filePath);
tv2.setText("文件名称" + fileName);

btn.setOnClickListener(new BtnOnclickListener());
}

/**
* ImageView的事件响应
* */
private class BtnOnclickListener implements View.OnClickListener{

@Override
public void onClick(View v) {
new Thread(new Runnable() {

@Override
public void run() {
// TODO Auto-generated method stub
Message message = Message.obtain();
String result="";
try {
QueryUploadUtil quu = new QueryUploadUtil(Base64Util.getBase64String(filePath+fileName), "temp.png");
result= quu.call(wsdl,wsdl);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
message.obj=result;
handler.sendMessage(message);
}
}).start();
}
}
}


可以去我的github上下载Demo,两个文件:一个Android客户端,一个服务端。下载地址:https://github.com/weifengzz/UploadFile_1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: