使用.NET框架、Web service實現Android的文件上傳(一)


上面是上傳結果的展示,下面具體講一下實現過程。

一、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字符串

 1 /**
 2  *得到經過處理的Base64字符串
 3  * Created by WFZ on 2015/12/7.
 4  */
 5 public class Base64Util {
 6     public static String getBase64String(String path) {
 7         byte[] byteArray = null;
 8         byteArray = Fileutil.readFileToByteArray(new File(path));
 9         String strBase64 = new String(Base64.encode(byteArray,0));
10         return strBase64;
11     }
12 }

2、讀取文件的工具類

 1 import java.io.ByteArrayOutputStream;
 2 import java.io.File;
 3 import java.io.FileInputStream;
 4 import java.io.FileNotFoundException;
 5 import java.io.IOException;
 6 /**
 7  * 讀取文件的工具類
 8  * Created by WFZ on 2015/12/7.
 9  */
10 public class Fileutil {
11     public static byte[] readFileToByteArray(File file) {
12         FileInputStream fileInputStream = null;
13         ByteArrayOutputStream byteArrayOutputStream = null;
14         try {
15             fileInputStream = new FileInputStream(file);
16             byteArrayOutputStream = new ByteArrayOutputStream();
17             byte[] bt = new byte[1024];
18             int len = 0;
19             while ((len = fileInputStream.read(bt)) != -1) {
20                 byteArrayOutputStream.write(bt, 0, len);
21             }
22             return byteArrayOutputStream.toByteArray();
23         } catch (FileNotFoundException e) {
24             // TODO Auto-generated catch block
25             e.printStackTrace();
26         } catch (IOException e) {
27             // TODO Auto-generated catch block
28             e.printStackTrace();
29         } finally {
30             if (fileInputStream != null) {
31                 try {
32                     fileInputStream.close();
33                 } catch (IOException e) {
34                     // TODO Auto-generated catch block
35                     e.printStackTrace();
36                 }
37             }
38             if (byteArrayOutputStream != null) {
39                 try {
40                     byteArrayOutputStream.close();
41                 } catch (IOException e) {
42                     // TODO Auto-generated catch block
43                     e.printStackTrace();
44                 }
45             }
46         }
47         return null;
48     }
49 }

3、上傳文件的工具類,這里需要soap的jar包

 1 import org.ksoap2.SoapEnvelope;
 2 import org.ksoap2.serialization.SoapObject;
 3 import org.ksoap2.serialization.SoapSerializationEnvelope;
 4 import org.ksoap2.transport.HttpTransportSE;
 5 
 6 /**
 7  *
 8  * Created by WFZ on 2015/12/7.
 9  */
10 public class QueryUploadUtil {
11     private String filename, base64string;
12 
13     public QueryUploadUtil(String base64str, String fileName) {
14         this.filename = fileName;
15         this.base64string = base64str;
16     }
17     // 需要實現Callable的Call方法
18     public String call(String wsdl,String url) throws Exception {
19         String str = "上傳失敗";
20         // TODO Auto-generated method stub
21         try {
22             //創建SoapObject對象,並指定WebService的命名空間和調用的方法名
23             SoapObject rpc = new SoapObject("http://tempuri.org/",
24                     "FileUploadByBase64String");
25             //設置WebService方法的參數
26             rpc.addProperty("base64string", base64string);
27             rpc.addProperty("fileName1", filename);
28             //第3步:創建SoapSerializationEnvelope對象,並指定WebService的版本
29             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
30                     SoapEnvelope.VER11);
31             // 設置bodyOut屬性
32             envelope.bodyOut = rpc;
33             envelope.dotNet = true;
34             envelope.setOutputSoapObject(rpc);
35             //創建HttpTransportSE對象,並指定WSDL文檔的URL
36             /**
37              * 創建WSDL文檔有三種方法:
38              * 在.NET中有三種方式生成WSDL:
39              * 1.在Web Service的URL后面加上WDSL需求,如下:
40              *  http://localhost/webExamples/simpleService.asmx?WSDL
41              * 2.使用disco.exe。在命令行中寫下如下的命令:
42              *  disco http://localhost/webExamples/simpleService.asmx
43              *3.使用System.Web.Services.Description命名空間下提供的類
44              * */
45             HttpTransportSE ht = new HttpTransportSE(wsdl);
46             ht.debug = false;
47             //調用WebService
48             ht.call(url, envelope);
49             //使用getResponse方法獲得WebService方法的返回結果
50             String result = String.valueOf(envelope.getResponse());
51             //這個地方是我自己設置的從webservice返回的結果,“1”表示上傳成功。
52             if (result.toString().equals("1"))
53                 str = "上傳成功";
54         } catch (Exception e) {
55             // TODO Auto-generated catch block
56             e.printStackTrace();
57             str = "上傳錯誤";
58         }
59         return str;
60     }
61 }

三、布局文件

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
 3     android:layout_height="match_parent"
 4     android:orientation="vertical"
 5     tools:context=".MainActivity">
 6     <TextView
 7         android:id="@+id/tv1"
 8         android:layout_width="match_parent"
 9         android:layout_height="wrap_content" />
10     <TextView
11         android:id="@+id/tv2"
12         android:layout_width="match_parent"
13         android:layout_height="wrap_content" />
14     <Button
15         android:id="@+id/btn"
16         android:layout_width="match_parent"
17         android:text="上傳"
18         android:layout_height="wrap_content" />
19     <ImageView
20         android:id="@+id/iv"
21         android:layout_width="wrap_content"
22         android:layout_height="wrap_content" />
23     <TextView
24         android:id="@+id/tv3"
25         android:layout_width="match_parent"
26         android:layout_height="wrap_content" />
27 </LinearLayout>

四、MainActivity文件

  1 import android.content.DialogInterface;
  2 import android.graphics.Bitmap;
  3 import android.graphics.BitmapFactory;
  4 import android.os.Handler;
  5 import android.os.Message;
  6 import android.support.v7.app.AppCompatActivity;
  7 import android.os.Bundle;
  8 import android.view.Menu;
  9 import android.view.MenuItem;
 10 import android.view.View;
 11 import android.widget.Button;
 12 import android.widget.ImageView;
 13 import android.widget.TextView;
 14 import android.widget.Toast;
 15 
 16 import com.lhgj.wfz.uploadfiles.utils.Base64Util;
 17 import com.lhgj.wfz.uploadfiles.utils.Fileutil;
 18 import com.lhgj.wfz.uploadfiles.utils.QueryUploadUtil;
 19 
 20 import java.io.File;
 21 
 22 public class MainActivity extends AppCompatActivity {
 23     private TextView tv1 = null;//上傳的文件地址
 24     private TextView tv2 = null;//上傳的文件名稱
 25     private TextView tv3 = null;//上傳是否成功提示
 26     private Button btn = null;//上傳按鈕
 27     private ImageView img = null;//圖片
 28     private  String filePath="/data/data/com.lhgj.wfz.uploadfiles/";//手機中文件存儲的位置
 29     private String fileName ="temp.jpg";//上傳的圖片
 30     private String wsdl ="http://192.168.15.4:1122/service/vedios/GetVedios.asmx?WSDL";//WSDL
 31     private String url ="http://192.168.15.4:1122/service/vedios/GetVedios.asmx/FileUploadByBase64String";//與webservice交互的地址
 32 
 33     /**
 34      * 由於上傳文件是一個耗時操作,需要開一個異步,這里我們使用handle
 35      * */
 36     private Handler handler = new Handler() {
 37         public void handleMessage(android.os.Message msg) {
 38             String string = (String) msg.obj;
 39             Toast.makeText(MainActivity.this, string, Toast.LENGTH_LONG).show();;
 40             tv3.setText(string);
 41         };
 42     };
 43 
 44     @Override
 45     protected void onCreate(Bundle savedInstanceState) {
 46         super.onCreate(savedInstanceState);
 47         setContentView(R.layout.activity_main);
 48         initView();
 49     }
 50 
 51     /**
 52      * 初始化view
 53      * */
 54     private void initView(){
 55         tv1 = (TextView) findViewById(R.id.tv1);
 56         tv2 = (TextView) findViewById(R.id.tv2);
 57         tv3 = (TextView) findViewById(R.id.tv3);
 58         btn = (Button) findViewById(R.id.btn);
 59         img = (ImageView) findViewById(R.id.iv);
 60 
 61         //設置顯示的圖片
 62         byte[] byteArray = null;
 63         byteArray = Fileutil.readFileToByteArray(new File(filePath+fileName));
 64         Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
 65                 byteArray.length);
 66         img.setImageBitmap(bitmap);
 67 
 68         //設置顯示的文本
 69         tv1.setText("文件位置:" + filePath);
 70         tv2.setText("文件名稱" + fileName);
 71 
 72         btn.setOnClickListener(new BtnOnclickListener());
 73     }
 74 
 75     /**
 76      * ImageView的事件響應
 77      * */
 78     private class BtnOnclickListener implements View.OnClickListener{
 79 
 80         @Override
 81         public void onClick(View v) {
 82             new Thread(new Runnable() {
 83 
 84                 @Override
 85                 public void run() {
 86                     // TODO Auto-generated method stub
 87                     Message message = Message.obtain();
 88                     String result="";
 89                     try {
 90                         QueryUploadUtil quu = new QueryUploadUtil(Base64Util.getBase64String(filePath+fileName), "temp.png");
 91                         result= quu.call(wsdl,wsdl);
 92                     } catch (Exception e) {
 93                         // TODO Auto-generated catch block
 94                         e.printStackTrace();
 95                     }
 96                     message.obj=result;
 97                     handler.sendMessage(message);
 98                 }
 99             }).start();
100         }
101     }
102 }

 


 

可以去我的github上下載Demo,兩個文件:一個Android客戶端,一個服務端。下載地址:https://github.com/weifengzz/UploadFile_1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM