Android to upload file function method _android

Source: Internet
Author: User
Tags stringbuffer

This article described as an Android upload file source code, each step of the implementation process are equipped with detailed comments, thinking more clearly, learning This example of the upload file code, you can deal with other formats file upload. Examples of the main implementation of uploading files to the server method, allow input, Output, do not use the cache, so that androiod upload files become easy.

The main functional code is as follows:

Package com.test;
Import Java.io.DataOutputStream;
Import Java.io.FileInputStream;
Import Java.io.InputStream;
Import java.net.HttpURLConnection;

Import Java.net.URL;
Import android.app.Activity;
Import Android.app.AlertDialog;
Import Android.content.DialogInterface;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.widget.Button;
Import Android.widget.TextView;  public class Main extends activity {/* variable declaration * newName: file name on server after uploading * uploadfile: File path to upload * ActionURL: Corresponding program path on server
  * * Private String newname= "image.jpg";
  Private String uploadfile= "/data/image.jpg";
  Private String actionurl= "http://l27.0.0.1/upload/upload.jsp";
  Private TextView MText1;
  Private TextView mText2;

  Private Button Mbutton;
   @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);

   Setcontentview (R.layout.main);
   MText1 = (TextView) Findviewbyid (R.ID.MYTEXT2);
   Mtext1.settext ("File path: \ n" +uploadfile); MText2 = (TextView) findViewbyid (R.ID.MYTEXT3);
   Mtext2.settext ("Upload URL: \ n" +actionurl);
   /* Set Mbutton onclick event handling/Mbutton = (Button) Findviewbyid (R.id.mybutton);
    Mbutton.setonclicklistener (New View.onclicklistener () {public void OnClick (View v) {uploadfile ();
  }
   });
   /* The method to upload files to server * * private void UploadFile () {String end = "\ r \ n";
   String Twohyphens = "--";
   String boundary = "* * *";
    try {URL url =new url (actionurl);
    HttpURLConnection con= (httpurlconnection) url.openconnection ();
    /* Allow input, Output, do not use cache */Con.setdoinput (TRUE);
    Con.setdooutput (TRUE);
    Con.setusecaches (FALSE);
    /* Set the Transmitting Method=post * * Con.setrequestmethod ("POST");
    /* Setrequestproperty * * Con.setrequestproperty ("Connection", "keep-alive");
    Con.setrequestproperty ("Charset", "UTF-8");
    Con.setrequestproperty ("Content-type", "multipart/form-data;boundary=" +boundary); 
/* Set DataOutputStream * * DataOutputStream ds =     New DataOutputStream (Con.getoutputstream ());
    Ds.writebytes (twohyphens + boundary + end); Ds.writebytes ("Content-disposition:form-data" + "name=\" file1\ "filename=\" "+ NewName +" "" + en
    D);  

    Ds.writebytes (end);
    /* Obtain the document FileInputStream * * FileInputStream fstream = new FileInputStream (uploadfile);
    /* Set each write 1024bytes/int buffersize = 1024;

    byte[] buffer = new Byte[buffersize];
    int length =-1; /* Read data from the file to the buffer */while (length = fstream.read (buffer)!=-1) {/* Write the data to the DataOutputStream/* Ds.write (b
    Uffer, 0, length);
    } ds.writebytes (end);

    Ds.writebytes (twohyphens + boundary + twohyphens + end);
    /* Close Streams * * fstream.close ();

    Ds.flush ();
    /* Get Response content * * InputStream is = Con.getinputstream ();
    int ch;
    StringBuffer b =new StringBuffer ();
    while (ch = is.read ())!=-1) {b.append ((char) ch); /* Will response Display in dialog/* ShowdiaLog (b.tostring (). Trim ());
   /* Close DataOutputStream * * Ds.close ();
   catch (Exception e) {ShowDialog ("" +e); }/* Displays the dialog method */private void ShowDialog (String mess) {new Alertdialog.builder (main.this). Settitle (" Message "). Setmessage (Mess). Setnegativebutton (" OK ", new Dialoginterface.onclicklistener () {public void oncli
  CK (dialoginterface dialog, int which) {}}). Show ();
 }
}

Readers can extend and refine the code if they feel they are not functional enough to make it more consistent with their application needs.

Related Article

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.