博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android调用Webservice发送文件
阅读量:5944 次
发布时间:2019-06-19

本文共 6347 字,大约阅读时间需要 21 分钟。

一服务器端C#

这里有三个上传方法
1.uploadFile( byte []bs, String fileName);
PC机操作是没有问题
2. uploadImage(String filename,String image);
//android大于1M上传会出问题(内存溢出),把文件件转换为Base64字符串上传
3. uploadResume(String filename,
String image, int tag); //android可以传大文件
using System;
using
System.Collections.Generic;
using System.Web;
using
System.Web.Services;
using System.IO;
///
/// Summary description for
service1
///
[WebService(Namespace = "")]
[WebServiceBinding(ConformsTo =
WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from
script, using ASP.NET AJAX, uncomment the following line.
//
[System.Web.Script.Services.ScriptService]
public class service1 :
System.Web.Services.WebService {
public service1 () {
//Uncomment the
following line if using designed
components
//InitializeComponent();
}
[WebMethod]
public string
HelloWorld(string str1) {
return str1+"成功";
}
[WebMethod]
public int
Add(int a, int b)
{
return a + b;
}
[WebMethod]
public int
uploadFile( byte []bs, String fileName){
FileStream out1 =null;
try
{
String
path=String.Format("{0:yyyyMMdd_hhmmss}_{1}",DateTime.Now,fileName);
String
newFile = HttpContext.Current.Server.MapPath("upload/"+path); //
上传文件存放路径
out1 = new FileStream(newFile, FileMode.CreateNew,
FileAccess.Write);
try {
out1.Write(bs,0,bs.Length);
} catch
(IOException e) {
// TODO Auto-generated catch block
;
}
} catch
(FileNotFoundException e) {
// TODO Auto-generated catch block
return
- 1 ;
} finally {
if (out1 != null ) {
try {
out1.Close();
}
catch (IOException e) {
// TODO Auto-generated catch
block
}
}
}
return 0 ;
}
[WebMethod]
//android大于1M上传会出问题(内存溢出)
public int uploadImage(String filename,String
image){
FileStream out1 =null;
byte
[]bs=Convert.FromBase64String(image);
try {
String
path=String.Format("{0:yyyyMMdd_hhmmss}_{1}",DateTime.Now,filename);
String
newFile = HttpContext.Current.Server.MapPath("upload/"+path); //
上传文件存放路径
out1 = new FileStream(newFile, FileMode.CreateNew,
FileAccess.Write);
try {
out1.Write(bs,0,bs.Length);
} catch
(IOException e) {
// TODO Auto-generated catch block
;
}
} catch
(FileNotFoundException e) {
// TODO Auto-generated catch block
return
- 1 ;
} finally {
if (out1 != null ) {
try {
out1.Close();
}
catch (IOException e) {
// TODO Auto-generated catch
block
}
}
}
return 0 ;
}
[WebMethod] //断点续传
public int
uploadResume(String filename, String image, int tag)
{
FileStream out1 =
null;
byte[] bs = Convert.FromBase64String(image);
try
{
String
newFile = HttpContext.Current.Server.MapPath("upload/" + filename); //
上传文件存放路径
if (tag ==
0)
{
if(File.Exists(filename))
File.Delete(filename);
out1 = new
FileStream(newFile, FileMode.CreateNew,
FileAccess.Write);
}
else
{
out1 = new FileStream(newFile,
FileMode.Append, FileAccess.Write);
}
try
{
out1.Write(bs, 0,
bs.Length);
}
catch (IOException e1)
{
// TODO Auto-generated catch
block
;
}
}
catch (FileNotFoundException e2)
{
// TODO
Auto-generated catch block
return -1;
}
finally
{
if (out1 !=
null)
{
try
{
out1.Close();
}
catch (IOException e)
{
//
TODO Auto-generated catch block
}
}
}
return tag;
}
}
二.客户端
要使用 ksoap2库

 

 

package cn.serverice;

import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.text.SimpleDateFormat;

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

import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Base64; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView;

public class Webserverice extends Activity {     /** Called when the activity is first created. */  private final String NAMESCROPE="http://mywebservice.cn/";  private final String METHOD_NAME="uploadResume";  private final String URL="http://192.168.1.18/3g/WebService.asmx";  private final String SOAP_ACTION="http://mywebservice.cn/uploadResume";  private Button btn;  private TextView txt1;    Handler handler=null;    //进程中调用view不安全

  String str1="";   //返回调用值         @Override     public void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.main);                 txt1=(TextView)findViewById(R.id.txt1);                 btn=(Button)findViewById(R.id.btnok);         btn.setOnClickListener(new OnClickListener(){                  @Override   public void onClick(View v) {    // TODO Auto-generated method stub           final String filename="/sdcard/DCIM/012.3gp";                               handler=new Handler();           @SuppressWarnings("unused")     Thread webserviceThread = new Thread(){             @Override      public void run(){               uploadTest(filename);                          }                                   };           webserviceThread.start();   }                      });            }     private void uploadTest(String filename)     {      SimpleDateFormat sDateFormat =new SimpleDateFormat("yyyy-MM-dd_hhmmss");         String file1=sDateFormat.format(new java.util.Date())+filename.substring(filename.indexOf("."));       try     {       FileInputStream fis=new FileInputStream(filename);       //ByteArrayOutputStream baos=new ByteArrayOutputStream();       byte []buffer=new byte[100*1024];       int count=0;       int i=0;       while((count=fis.read(buffer))>=0){        String uploadBuffer=new String(Base64.encode(buffer,0,count,Base64.DEFAULT));           showServerice(uploadBuffer,file1,i);  //续传                     for(int j=0;j<1000;j++);                     i++;        }              fis.close();      }catch(FileNotFoundException e){        e.printStackTrace();      }catch(IOException e){         e.printStackTrace();       }     }

    public void showServerice(String image,String file1,int tag)     {      SoapObject request = new SoapObject(NAMESCROPE, METHOD_NAME);      SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);            try {    request.addProperty("filename", file1);    request.addProperty("image",image);    request.addProperty("tag",tag);            envelope.bodyOut=request;     envelope.dotNet=true;    envelope.setOutputSoapObject(request);   } catch (Exception e1) {    // TODO Auto-generated catch block    Log.e("Error","错误1");   }            HttpTransportSE ht=new HttpTransportSE(URL);      ht.debug=true;      try      {       ht.call(SOAP_ACTION, envelope);       SoapObject result = (SoapObject) envelope.bodyIn;                    str1=result.getProperty(0).toString();                         //txt1.setText("uploadImage(filename,image)="+str1+" 成功!"); 在进程中不安全,要加入Runnable             handler.post(runnableUi);             }catch(Exception e){       Log.d("Error",e.getMessage());      }           }     Runnable runnableUi=new  Runnable(){      //给文本框设值          @Override             public void run() {                  //更新界面            txt1.setText("uploadImage(filename,image)="+str1+" 成功!");             }                         };          

}

 

转载地址:http://xuwxx.baihongyu.com/

你可能感兴趣的文章
手机H5显示一像素的细线
查看>>
Menu 菜单栏
查看>>
Integer跟int的区别(备份回忆)
查看>>
集合解析
查看>>
详解分布式应用程序协调服务Zookeeper
查看>>
软件工程之构建之法
查看>>
UVa 10902
查看>>
Mathf.Sin正弦
查看>>
禁止浏览器缓存js
查看>>
【Redis】安装PHP的redis驱动(二)
查看>>
什么是序列化,为什么要序列化
查看>>
Java保留小数点后有效数字
查看>>
C++中一些类和数据结构的大小的总结
查看>>
mysql开启binlog
查看>>
ctrl + z fg bg
查看>>
工作流引擎Oozie(一):workflow
查看>>
struct框架
查看>>
Deep Learning(深度学习)相关网站
查看>>
设置Eclipse编码方式
查看>>
分布式系统唯一ID生成方案汇总【转】
查看>>