Android Call WebService send file

Source: Internet
Author: User
<span id="Label3"></p><p>One server-side C #<br>Here are three ways to upload<br>1.uploadFile (byte []bs, String fileName];<br>PC operation is no problem<br>2. Uploadimage (String filename,string image);<br>Android larger than 1M upload will be problematic (memory overflow), convert files to Base64 string upload<br>3. Uploadresume (String filename,<br>String image, int tag); Android can upload large files<br><br>Using System;<br>Using<br>System.Collections.Generic;<br>Using system.web;<br>Using<br>System.Web.Services;<br>Using system.io;<br>///<br>Summary description for<br>Service1<br>///<br>[WebService (Namespace = "http://myserver1.cn/")]<br>[webservicebinding (conformsto =<br>wsiprofiles.basicprofile1_1)]<br>to, this Web Service to is called from<br>script, using asp. AJAX, uncomment the following line.<br>//<br>[System.Web.Script.Services.ScriptService]<br>public class Service1:<br>System.Web.Services.WebService {<br>Public Service1 () {<br>Uncomment the<br>Following line if using designed<br>Components<br>InitializeComponent ();<br>}<br>[WebMethod]<br>public string<br>HelloWorld (string Str1) {<br>return str1+ "success";<br>}<br>[WebMethod]<br>public int<br>ADD (int a, int B)<br>{<br>Return a + b;<br>}<br>[WebMethod]<br>public int<br>UploadFile (byte []bs, String FileName) {<br><br>FileStream OUT1 =null;<br>Try<br>{<br>String<br>Path=string.format ("{0:yyyymmdd_hhmmss}_{1}", datetime.now,filename);<br>String<br>NewFile = HttpContext.Current.Server.MapPath ("upload/" +path); //<br>Upload file storage path<br>OUT1 = new FileStream (newFile, filemode.createnew,<br>fileaccess.write);<br>try {<br>out1. Write (bs,0,bs. Length);<br>} catch<br>(ioexception E) {<br>TODO auto-generated Catch block<br>;<br>}<br>} catch<br>(filenotfoundexception E) {<br>TODO auto-generated Catch block<br><br>Return<br>-1;<br>} finally {<br>If (out1! = Null) {<br>try {<br>out1. Close ();<br>}<br>Catch (ioexception E) {<br>TODO auto-generated Catch<br>Block<br><br>}<br>}<br>}<br>Return 0;<br>}<br>[WebMethod]<br>Android larger than 1M upload will be problematic (memory Overflow)<br>public int Uploadimage (String filename,string<br>Image) {<br><br>FileStream OUT1 =null;<br>Byte<br>[]bs=convert.frombase64string (image);<br>try {<br>String<br>Path=string.format ("{0:yyyymmdd_hhmmss}_{1}", datetime.now,filename);<br>String<br>NewFile = HttpContext.Current.Server.MapPath ("upload/" +path); //<br>Upload file storage path<br>OUT1 = new FileStream (newFile, filemode.createnew,<br>fileaccess.write);<br>try {<br>out1. Write (bs,0,bs. Length);<br>} catch<br>(ioexception E) {<br>TODO auto-generated Catch block<br>;<br>}<br>} catch<br>(filenotfoundexception E) {<br>TODO auto-generated Catch block<br><br>Return<br>-1;<br>} finally {<br>If (out1! = Null) {<br>try {<br>out1. Close ();<br>}<br>Catch (ioexception E) {<br>TODO auto-generated Catch<br>Block<br><br>}<br>}<br>}<br>Return 0;<br>}<br>[WebMethod]//breakpoint Continuation<br>public int<br>Uploadresume (string filename, string image, int Tag)<br>{<br>FileStream OUT1 =<br>Null<br>byte[] bs = convert.frombase64string (image);<br>Try<br>{<br><br>String<br>NewFile = HttpContext.Current.Server.MapPath ("upload/" + filename); //<br>Upload file storage path<br>if (tag = =<br>0)<br>{<br><br>If (file.exists (filename))<br>File.delete (filename);<br>OUT1 = new<br>FileStream (newFile, filemode.createnew,<br>fileaccess.write);<br>}<br>Else<br>{<br>OUT1 = new FileStream (newFile,<br>filemode.append, fileaccess.write);<br>}<br>Try<br>{<br>out1. Write (bs, 0,<br>Bs. Length);<br>}<br>Catch (ioexception E1)<br>{<br>TODO auto-generated Catch<br>Block<br>;<br>}<br>}<br>Catch (filenotfoundexception E2)<br>{<br>Todo<br>Auto-generated Catch block<br>return-1;<br>}<br>Finally<br>{<br>If (out1! =<br>Null<br>{<br>Try<br>{<br>out1. Close ();<br>}<br>Catch (ioexception E)<br>{<br>//<br>TODO auto-generated Catch block<br>}<br>}<br>}<br>Return tag;<br>}<br>}<br>TWO. Client<br>To use the KSOAP2 library</p><p><p></p></p><p><p></p></p><p><p>Package cn.serverice;</p></p><p><p>Import java.io.FileInputStream; Import java.io.FileNotFoundException; Import java.io.IOException; Import java.text.SimpleDateFormat;</p></p><p><p>Import org.ksoap2.SoapEnvelope; Import org.ksoap2.serialization.SoapObject; Import org.ksoap2.serialization.SoapSerializationEnvelope; Import org.ksoap2.transport.HttpTransportSE;</p></p><p><p>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;</p></p><p><p> Public class Webserverice extends activity {   /** called if the activity is first Created. */  ;p rivate 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;   //process Call View unsafe </p></p><p>  String str1= "";  //return call value         @Override     public void ONCR Eate (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 ();   }                  & Nbsp;  });           }     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); //cont.                       for (int j=0;j<1000;j++);                     i+ +;       }              Fis.close ();     }catch (filenotfoundexception e) {       e.printstacktrace () ;     }catch (ioexception e) {        e.printstacktrace ();      }    }</p><p>    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 "," 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+ "success!"); Not secure in the process, to join runnable             handler.post (runnableui);             }catch (Exception e) {      log.d (" Error ", e.getmessage ());      }          }     Runnable runnableui=new& nbsp Runnable () {     //set values for text boxes           @Override              public void run () {                  //update interface              Txt1.settext ("uploadimage (filename,image) =" +str1+ "success!");            }                         };           </p><p><p>}</p></p><p><p></p></p><p><p>Android Call WebService send file</p></p></span>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.