Upload Android images to the PHP Server instance asynchronously-php Tutorial

Source: Internet
Author: User
Android image upload to PHP Server instance background asynchronously

I have uploaded a lot of files to the java server on the Internet for a long time and found the files to be uploaded to php. The idea is similar to what I originally thought, that is, POST. Look at the code.

PHP code

PHP code

  1. $ Target_path = "./upload/"; // receiving file directory
  2. $ Target_path = $ target_path. basename ($ _ FILES ['uploadfile'] ['name']);
  3. If (move_uploaded_file ($ _ FILES ['uploadfile'] ['tmp _ name'], $ target_path )){
  4. Echo "The file". basename ($ _ FILES ['uploadfile'] ['name']). "has been uploaded ";
  5. } Else {
  6. Echo "There was an error uploading the file, please try again! ". $ _ FILES ['uploadfile'] ['error'];
  7. }
  8. ?>

Android code

Main Upload 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 transmission to effectively prevent the phone from crashing due to insufficient memory
  12. HttpURLConnection. setChunkedStreamingMode (128*1024); // 128 K
  13. // Allow input and output streams
  14. HttpURLConnection. setDoInput (true );
  15. HttpURLConnection. setDoOutput (true );
  16. HttpURLConnection. setUseCaches (false );
  17. // Use the POST method
  18. HttpURLConnection. setRequestMethod ("POST ");
  19. HttpURLConnection. setRequestProperty ("Connection", "Keep-Alive"); // Keep the Connection
  20. HttpURLConnection. setRequestProperty ("Charset", "UTF-8"); // encoding
  21. HttpURLConnection. setRequestProperty ("Content-Type ",
  22. "Multipart/form-data; boundary =" + boundary); // POST the passed 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 FCM = new FileInputStream (srcPath); // File input stream, written to memory
  32. Byte [] buffer = new byte [0, 8192]; // 8 k
  33. Int count = 0;
  34. // Read the file
  35. While (count = fs. read (buffer ))! =-1)
  36. {
  37. Dos. write (buffer, 0, count );
  38. }
  39. FCM. close ();
  40. Dos. writeBytes (end );
  41. Dos. writeBytes (twoHyphens + boundary + twoHyphens + end );
  42. Dos. flush ();
  43. InputStream is = httpURLConnection. getInputStream (); // http input, that is, the returned result is obtained.
  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 after Android 4.0 are required to be performed in non-UI threads, I will use the previous AsyncTask ~

AsyncTask portal: http://www.cnblogs.com/yydcdut/p/3707960.html

In this class, put the upload operation in doInBackground, and you can see ProgressDialog to display the upload quantity:

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 * 100)/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 permissions:

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.