Android images are uploaded asynchronously to the PHP server instance

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 code

    1. $target _path = "./upload/"; Receive file directory
    2. $target _path = $target _path. basename ($_files [' uploadedfile '] [' name ']);
    3. if (Move_uploaded_file ($_files [' uploadedfile '] [' tmp_name '], $target _path)) {
    4. echo "The file". basename ($_files [' uploadedfile '] [' name ']). "has been uploaded";
    5. } else {
    6. echo "There was a error uploading the file, please try again!". $_files [' UploadedFile '] [' ERROR '];
    7. }
    8. ?>

Android Code

Upload the main code:

Java code

  1. private void UploadFile (String uploadurl)
  2. {
  3. String end = "\ r \ n";
  4. String Twohyphens = "--";
  5. String boundary = "******";
  6. Try
  7. {
  8. URL url = new URL (uploadurl);
  9. HttpURLConnection httpurlconnection = (httpurlconnection) URL
  10. . OpenConnection (); HTTP connection
  11. Set the stream size for each transfer to effectively prevent the phone from crashing due to low memory
  12. Httpurlconnection.setchunkedstreamingmode (128 * 1024); 128K
  13. Allow input/output stream
  14. Httpurlconnection.setdoinput (TRUE);
  15. Httpurlconnection.setdooutput (TRUE);
  16. Httpurlconnection.setusecaches (FALSE);
  17. Using the Post method
  18. Httpurlconnection.setrequestmethod ("POST");
  19. Httpurlconnection.setrequestproperty ("Connection", "keep-alive"); Keep connected
  20. Httpurlconnection.setrequestproperty ("Charset", "UTF-8"); Coding
  21. Httpurlconnection.setrequestproperty ("Content-type",
  22. "multipart/form-data;boundary=" + boundary); Post passes past the encoding
  23. DataOutputStream dos = new DataOutputStream (
  24. Httpurlconnection.getoutputstream ()); Output stream
  25. Dos.writebytes (twohyphens + boundary + end);
  26. Dos.writebytes ("Content-disposition:form-data; Name=\ "Uploadedfile\"; Filename=\ ""
  27. + srcpath.substring (Srcpath.lastindexof ("/") + 1)
  28. + "\""
  29. + end);
  30. Dos.writebytes (end);
  31. FileInputStream fis = new FileInputStream (Srcpath); File input stream, written into memory
  32. byte [] buffer = new byte [8192]; 8k
  33. int count = 0;
  34. Read file
  35. while ((count = fis.read (buffer))! =-1)
  36. {
  37. Dos.write (buffer, 0, count);
  38. }
  39. Fis.close ();
  40. Dos.writebytes (end);
  41. Dos.writebytes (twohyphens + boundary + twohyphens + end);
  42. Dos.flush ();
  43. InputStream is = Httpurlconnection.getinputstream (); HTTP input, which results in the return
  44. InputStreamReader ISR = new InputStreamReader (IS, "utf-8");
  45. BufferedReader br = new BufferedReader (ISR);
  46. String result = Br.readline ();
  47. Toast.maketext (this, result, Toast.length_long). Show (); Output the result
  48. Dos.close ();
  49. Is.close ();
  50. } catch (Exception e)
  51. {
  52. E.printstacktrace ();
  53. Settitle (E.getmessage ());
  54. }
  55. }

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:

Java code

    1. Read file
    2. Bytesread = fileinputstream.read (buffer, 0, buffersize);
    3. while (Bytesread > 0) {
    4. Outputstream.write (buffer, 0, buffersize);
    5. length + = buffersize;
    6. progress = (int) ((length *)/totalsize);
    7. Publishprogress (progress);
    8. bytesavailable = Fileinputstream.available ();
    9. buffersize = Math.min (bytesavailable, maxBufferSize);
    10. Bytesread = fileinputstream.read (buffer, 0, buffersize);
    11. }
    12. Outputstream.writebytes (Lineend);
    13. Outputstream.writebytes (twohyphens + boundary + twohyphens
    14. + lineend);
    15. Publishprogress (100);

Also, pay attention to the authority yo:

xml/html Code

    1. < uses-permission Android:name = "Android.permission.INTERNET"/>
  • 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.