Android uploads files to the Web server, and PHP receives files (2)

Source: Internet
Author: User

Next to the previous article "android uploads files to the Web server, PHP receives files (1)". This time, the progress is displayed based on the previous steps. The Java code is as follows:

Package COM. lenovo. uptest; import Java. io. datainputstream; import Java. io. dataoutputstream; import Java. io. file; import Java. io. fileinputstream; import java.net. httpurlconnection; import java.net. URL; import android. app. activity; import android. app. alertdialog; import android. app. progressdialog; import android. content. dialoginterface; import android. OS. asynctask; import android. OS. bundle; import android. view. VI EW; import android. widget. button; import android. widget. textview; public class uploadtestactivity extends activity {/** called when the activity is first created. * // *** Upload File to Web server with progress status, client: Android; * server: PhP ***/private textview mtv1 = NULL; private textview mtv2 = NULL; private button bupload = NULL; private string uploadfile = "/sdcard/testimg.jpg"; private Str Ing actionurl = "http: // 10.100.1.208/receive_file.php"; @ overridepublic void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); mtv1 = (textview) findviewbyid (R. id. mtv1); mtv1.settext ("file path: \ n" + uploadfile); mtv2 = (textview) findviewbyid (R. id. mtv2); mtv2.settext ("Upload address: \ n" + actionurl); bupload = (button) findviewbyid (R. id. bupload); bupload. setonclickl Istener (new view. onclicklistener () {@ overridepublic void onclick (view v) {// todo auto-generated method stubfileuploadtask fileuploadtask = new fileuploadtask({{fileuploadtask.exe cute ();}});} // show dialog methodprivate void showdialog (string mess) {New alertdialog. builder (uploadtestactivity. this ). settitle ("message "). setmessage (MESS ). setnegativebutton ("OK", new dialoginterface. onclicklistener (){@ Overridepublic void onclick (dialoginterface dialog, int which ){}}). show ();} class fileuploadtask extends asynctask <object, integer, void> {private progressdialog diask = NULL; httpurlconnection connection = NULL; dataoutputstream outputstream = NULL; datainputstream inputstream = NULL; // The file path to uploadstring pathtoourfile = "/sdcard/testimg.jpg"; // The server address to process uploaded files Tring urlserver = "http: // 10.100.1.208/receive_file.php"; string lineend = "\ r \ n"; string twohyphens = "--"; string boundary = "*****"; file uploadfile = new file (pathtoourfile); long totalsize = uploadfile. length (); // get size of file, bytes @ overrideprotected void onpreexecute () {dialog = new progressdialog (uploadtestactivity. this); dialog. setmessage ("Uploading... "); dialog. setindeterminate (false); dialog. se Tprogressstyle (progressdialog. style_horizontal); dialog. setprogress (0); dialog. show () ;}@ overrideprotected void doinbackground (object... arg0) {long length = 0; int progress; int bytesread, bytesavailable, buffersize; byte [] buffer; int maxbuffersize = 256*1024; // 256 kbtry {fileinputstream = new fileinputstream (new file (pathtoourfile); Url url = new URL (urlserver); connection = (httpurlc Onnection) URL. openconnection (); // set size of every block for postconnection. setchunkedstreamingmode (256*1024); // 256kb // allow inputs & outputsconnection. setdoinput (true); connection. setdooutput (true); connection. setusecaches (false); // enable post methodconnection. setrequestmethod ("Post"); connection. setrequestproperty ("connection", "keep-alive"); connection. setrequestproperty ("charset", "UTF-8 "); Connection. setrequestproperty ("Content-Type", "multipart/form-data; boundary =" + boundary); outputstream = new dataoutputstream (connection. getoutputstream (); outputstream. writebytes (twohyphens + boundary + lineend); outputstream. writebytes ("content-Disposition: Form-data; name = \" uploadedfile \ "; filename = \" "+ pathtoourfile +" \ "" + lineend); outputstream. writebytes (lineend); bytesavailable = fileinputstre Am. available (); buffersize = math. min (bytesavailable, maxbuffersize); buffer = new byte [buffersize]; // read filebytesread = fileinputstream. read (buffer, 0, buffersize); While (bytesread> 0) {outputstream. write (buffer, 0, buffersize); Length + = buffersize; Progress = (INT) (length * 100)/totalsize); publishprogress (Progress); bytesavailable = fileinputstream. available (); buffersize = math. min (bytesavai Lable, maxbuffersize); bytesread = fileinputstream. read (buffer, 0, buffersize);} outputstream. writebytes (lineend); outputstream. writebytes (twohyphens + boundary + twohyphens + lineend); publishprogress (100); // responses from the server (code and message) int serverresponsecode = connection. getresponsecode (); string serverresponsemessage = connection. getresponsemessage ();/* display response in dialog * // toast t Oast = toast. maketext (uploadtestactivity. this, "" // + serverresponsemessage. tostring (). trim (), // toast. length_long); // showdialog (serverresponsemessage. tostring (). trim ();/* Get Response content * // inputstream is = connection. getinputstream (); // int ch; // stringbuffer SBF = new stringbuffer (); // while (CH = is. read ())! =-1) {// SBF. append (char) CH); //} // showdialog (SBF. tostring (). trim (); fileinputstream. close (); outputstream. flush (); outputstream. close ();} catch (exception ex) {// Exception Handling // showdialog ("" + ex); // Toast = toast. maketext (uploadtestactivity. this, "" + // ex, // toast. length_long);} return NULL;} @ overrideprotected void onprogressupdate (integer... progress) {dialog. setprogress (Progress [0]);} @ overrideprotected void onpostexecute (void result) {try {dialog. dismiss (); // todo auto-generated method stub} catch (exception e ){}}}}

The server is still the same as before.

Asynctask is used here, which makes it easier to create a task that needs to interact with the user interface for a long time. It is suitable for simple asynchronous processing and can be implemented without the use of threads and handler.
Asynctask is an abstract class. asynctask defines three generic types: Params, SS, and result.
Input parameters for Params startup task execution, such as the URL of the HTTP request.
Percentage of progress background tasks.
Result: The result returned when the task is executed in the background, such as string.

The execution of asynctask is divided into four steps. Each step corresponds to a callback method, which should not be called by the application. All developers need to do is implement these methods.
1) subclass asynctask
2) implement one or more of the following methods defined in asynctask
Onpreexecute (), this method will be called by the UI thread before the actual background operation is executed. You can make some preparations in this method, such as displaying a progress bar on the interface.
Doinbackground (Params...) will be executed immediately after the onpreexecute method is executed. This method runs in the background thread. Here, we will primarily perform those time-consuming background computing tasks. You can call publishprogress to update the real-time task progress. This method is an abstract method and must be implemented by sub-classes.
Onprogressupdate (Progress...), after the publishprogress method is called, UI thread will call this method to display the progress of the task on the interface, for example, display through a progress bar.
Onpostexecute (result). After doinbackground is executed, the onpostexecute method will be called by the UI thread, and the background computing result will be passed to the UI thread through this method.

To correctly use the asynctask class, the following guidelines must be followed:
1) The task instance must be created in the UI thread.
2) The execute method must be called in the UI thread.
3) do not manually call the onpreexecute (), onpostexecute (result), doinbackground (Params...), onprogressupdate (Progress...) methods.
4) The task can only be executed once. Otherwise, exceptions may occur during multiple calls.
The doinbackground method and the onpostexecute parameter must correspond to each other. These two parameters are specified in the generic parameter list declared by asynctask. The first parameter is the parameter accepted by doinbackground, and the second parameter is the parameter indicating the progress, the third is the doinbackground return and the parameters passed in by onpostexecute.

The running result is as follows:

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.