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

Source: Internet
Author: User

Android uploads files to the server. Generally, the HTTP protocol is constructed to simulate the webpage POST method for file transmission. The server can use JavaServlet or PHP to receive the files to be transmitted. It is common to use assumervlet to receive files. Here we will introduce a simple example of using PHP to receive files on the server side.

The server code is relatively simple and receives the transmitted files:

<? PHP $ target_path = ". /upload/"; // Receiving File directory $ target_path = $ target_path. basename ($ _ FILES ['uploadfile'] ['name']); If (move_uploaded_file ($ _ FILES ['uploadfile'] ['tmp _ name'], $ target_path) {echo "the file ". basename ($ _ FILES ['uploadfile'] ['name']). "has been uploaded";} else {echo "There was an error uploading the file, please try again! ". $ _ FILES ['uploadfile'] ['error'];}?>

Mobile client code:

Package COM. figo. uploadfile; import Java. io. bufferedreader; import Java. io. dataoutputstream; import Java. io. fileinputstream; import Java. io. inputstream; import Java. io. inputstreamreader; import java.net. httpurlconnection; import java.net. URL; import android. app. activity; import android. OS. bundle; import android. view. view; import android. widget. button; import android. widget. textview; import android. widget. toast; Public class uploadfileactivity extends activity {// file path to be uploaded. Theoretically, any file can be transmitted. In actual use, private string uploadfile = "/sdcard/testimg.jpg" can be processed as needed "; private string srcpath = "/sdcard/testimg.jpg"; // The processing page for receiving files on the server. Here, change it to your own private string actionurl = "http: // 10.100.1.208/receive_file.php "; private textview mtext1; private textview mtext2; private button mbutton; @ override public void oncreate (bundle savedin Stancestate) {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 the onclick event processing for mbutton */mbutton = (button) findviewbyid (R. id. mybutton); mbutton. setonclicklistener (new view. onclicklistener () {@ override P Ublic void onclick (view v) {uploadfile (actionurl) ;}});}/* upload the file to the server, uploadurl: processing page of received files */private void uploadfile (string uploadurl) {string end = "\ r \ n"; string twohyphens = "--"; string boundary = "*******"; try {URL url = new URL (uploadurl); httpurlconnection = (httpurlconnection) URL. openconnection (); // sets the stream size for each transmission, which can effectively prevent the phone from crashing due to insufficient memory. // This method is used to enable HTTP without any internal buffer when the content length is unknown in advance. The stream of the Request body. Httpurlconnection. setchunkedstreamingmode (128*1024); // 128 K // allow the input/output stream httpurlconnection. setdoinput (true); httpurlconnection. setdooutput (true); httpurlconnection. setusecaches (false); // use the POST method httpurlconnection. setrequestmethod ("Post"); httpurlconnection. setrequestproperty ("connection", "keep-alive"); httpurlconnection. setrequestproperty ("charset", "UTF-8"); httpurlconnection. setrequestpropert Y ("Content-Type", "multipart/form-data; boundary =" + boundary); dataoutputstream dos = new dataoutputstream (httpurlconnection. getoutputstream (); dos. writebytes (twohyphens + boundary + end); dos. writebytes ("content-Disposition: Form-data; name = \" uploadedfile \ "; filename = \" "+ srcpath. substring (srcpath. lastindexof ("/") + 1) + "\" "+ end); dos. writebytes (end); fileinputstream FCM = new fileinputstre Am (srcpath); byte [] buffer = new byte [8192]; // 8 K int COUNT = 0; // read the file while (COUNT = FCM. read (buffer ))! =-1) {dos. write (buffer, 0, count);} FD. close (); dos. writebytes (end); dos. writebytes (twohyphens + boundary + twohyphens + end); dos. flush (); inputstream is = httpurlconnection. getinputstream (); inputstreamreader ISR = new inputstreamreader (is, "UTF-8"); bufferedreader BR = new bufferedreader (ISR); string result = BR. readline (); toast. maketext (this, result, toast. length_long ). show (); dos. close (); is. close ();} catch (exception e) {e. printstacktrace (); settitle (E. getmessage ());}}}

Add the network access permission to the androidmanifest. xml file:

<uses-permission android:name="android.permission.INTERNET" />

Running result:

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.