Android--Images uploaded asynchronously to the PHP server

Source: Internet
Author: User
Tags php server

Background

On the Internet many uploaded to the Java server, looking for a long time, found the upload to PHP, thinking and I thought the same, is post past. Don't say much nonsense, just look at the code.

PHP code

<?PHP$target _path= "./upload/";//Receive file directory$target _path=$target _path.basename($_files[' UploadedFile '] [' Name ']);if(Move_uploaded_file($_files[' UploadedFile '] [' Tmp_name '],$target _path)) {   Echo"The file".basename($_files[' UploadedFile '] [' name ']). "has been uploaded";} Else{   Echo"There was a error uploading the file, please try again!".$_files[' UploadedFile '] [' Error '];}?>

Android Code

Upload the main code:

Private voiduploadfile (String uploadurl) {string End= "\ r \ n"; String Twohyphens= "--"; String Boundary= "******"; Try{URL URL=NewURL (Uploadurl); HttpURLConnection HttpURLConnection=(httpurlconnection) URL. OpenConnection ();//HTTP Connection//set the stream size for each transfer to effectively prevent the phone from crashing due to low memory//This method is used to enable a stream that does not have an internally buffered HTTP request body when the content length is not known beforehand. Httpurlconnection.setchunkedstreamingmode (128 * 1024);//128K//allow input/output streamHttpurlconnection.setdoinput (true); Httpurlconnection.setdooutput (true); Httpurlconnection.setusecaches (false); //using the Post methodHttpurlconnection.setrequestmethod ("POST"); Httpurlconnection.setrequestproperty ("Connection", "keep-alive");//Keep ConnectedHttpurlconnection.setrequestproperty ("Charset", "UTF-8");//CodingHttpurlconnection.setrequestproperty ("Content-type",          "multipart/form-data;boundary=" + boundary);//Post passes past the encodingDataOutputStream dos=NewDataOutputStream (Httpurlconnection.getoutputstream ());//output StreamDos.writebytes (Twohyphens + boundary +end); Dos.writebytes ("Content-disposition:form-data; Name=\ "Uploadedfile\"; Filename=\ "" + srcpath.substring (Srcpath.lastindexof ("/") + 1)          + "\""          +end);      Dos.writebytes (end); FileInputStream FIS=NewFileInputStream (Srcpath);//file input stream, written into memory      byte[] buffer =New byte[8192];//8k      intCount = 0; //Read File       while((count = fis.read (buffer))! =-1) {dos.write (buffer,0, Count);      } fis.close ();      Dos.writebytes (end); Dos.writebytes (Twohyphens+ Boundary + Twohyphens +end);      Dos.flush (); InputStream is= Httpurlconnection.getinputstream ();//http input, which results in the returnInputStreamReader ISR =NewInputStreamReader (IS, "Utf-8"); BufferedReader BR=NewBufferedReader (ISR); String result=Br.readline (); Toast.maketext ( This, result, Toast.length_long). Show ();//Output The resultDos.close ();    Is.close (); } Catch(Exception e) {e.printstacktrace ();    Settitle (E.getmessage ()); }  }

Because the time-consuming operations required after Android 4.0 are operating in a non-UI thread, the front asynctask will be used.

Asynctask Portal: http://www.cnblogs.com/yydcdut/p/3707960.html

In this class, the upload operation is placed in the Doinbackground, you can have progressdialog show how much uploaded:

//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 (bytesavailable, maxBufferSize); Bytesread= fileinputstream.read (buffer, 0, buffersize);            } outputstream.writebytes (Lineend); Outputstream.writebytes (Twohyphens+ Boundary +Twohyphens+lineend); Publishprogress (100);

Also, pay attention to the authority yo:

<android:name= "Android.permission.INTERNET"/>

I'm the dividing line of the king of the Land Tiger.

Source code: HTTP://PAN.BAIDU.COM/S/1DD1QX01

Update.zip

Reference: http://blog.csdn.net/sxwyf248/article/details/7012496

Reprint Please specify source: http://www.cnblogs.com/yydcdut/p/3720635.html

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.